Solved

Populate 2 dropdown select lists based on change event from 1st

Posted on 2014-11-15
14
399 Views
Last Modified: 2014-11-17
I have a dropdown list that triggers a change event that populates a second select list via jquery and php. What I need to do is, when the first event is triggered, populate dropdown 2 with the callback data and then query the database with the value of dropdown 2 and place result in dropdown 3.

 Where I am stuck is that I do not know how to query db from this sort of event.

I have posted the code I am currently using and would be grateful for any help with this as I am not sure what direction to go. Many thanks.

jquery code

$(function() {
  $("#dstr_dept").change(function() {
    $(this).after('<div id="loader"><imgages src="img/loading.gif" alt="loading files" /></div>');
    $.get('loadboxDstrsubcat.php?dstrdept=' + $(this).val(), function(data) {
      $("#box_dstr").html(data);
      $('#loader').slideUp(200, function() {
        $(this).remove();
        $("#box_dstr").trigger("chosen:updated"); 
      });
    });
  });
});

Open in new window


php code

<?php
 session_start();
?>

<?php
    include('../Connections/domain.php');

    $dstrdept = $_GET['cltdstrdept'];
    $customer = $_SESSION['kt_idcode_usr'];

    mysql_select_db($database_domain, $domain);
    $query = "SELECT name FROM departments WHERE code = '".$dstrdept."' ORDER BY name ASC";
    $result = mysql_query($query) or die (mysql_error());

    if (mysql_num_rows($result) > 0) {

    echo "<script type=text/javascript>\n";
    echo "$(function() {\n";
    echo "$(\".noBdstrBoxes\").html('')\n";
    echo "$('#dstr_dept').attr('data-placeholder', \"Choose your dept...\").prop('disabled', false)\n";
    //echo "$(\"#box_dstr\").prop('disabled', false)\n";
    //echo "$('#Frtv').show()\n";
    echo "});\n";
    echo "</script>\n";

    // This returns the data of departments
    while($row = mysql_fetch_array($result)) {
    echo "<option value='$row[name]'>$row[name]</option>";
    }    

    } else {

    echo "<script type=text/javascript>\n";
    echo "$(function() {\n";
    echo "$('.noBdstrBoxes').html('ERROR: There are no boxes to destroy in that dept. Please select another.').css({\"color\":\"red\", \"margin\": \"-6px 0 10px 22px\", \"font-size\": \"12px\", \"font-family\": \"Verdana, Geneva, sans-serif\"})\n";
    echo "$('#box_dstr').attr('data-placeholder', \"No boxes to display...\").prop('disabled', true)\n";
    echo "});\n";
    echo "</script>\n";

    //echo "<option value='No boxes in that dept'>No boxes in that dept</option>";

    }
?>

Open in new window


html code

<div class="fieldset">
          <h1><span>Select a Customer</span></h1>
          <p>
            <select data-placeholder="Choose a customer..." class="chosen-select" style="width:250px;" name="dstr_customer" id="dstr_customer">
              <option value=""></option>
                <option value="DEMO">DEMO</option>
                <option value="DEMO2">DEMO2</option>
                <option value="DEMO3">DEMO2</option>
                <option value="DEMO4">DEMO2</option>
            </select>
            <span></span>
            <a href="javascript:void(0)" style="margin-left:10px;" class="tooltip" title="Please select a dept where the box to be destroyed is stored.">Help</a>
          </p>
        </div>

<div class="fieldset">
          <h1><span>Select a Department</span></h1>
          <p>
            <select data-placeholder="Choose a dept..." class="chosen-select" style="width:250px;" name="dstr_dept" id="dstr_dept">
              <option value=""></option>

            </select>
            <span></span>
            <a href="javascript:void(0)" style="margin-left:10px;" class="tooltip" title="Please select a dept where the box to be destroyed is stored.">Help</a>
          </p>
        </div>

<div class="fieldset">
          <h1><span>Select an Address</span></h1>
          <p>
            <select data-placeholder="Choose an address..." class="chosen-select" style="width:250px;" name="dstr_address" id="dstr_address">
              <option value=""></option>

            </select>
            <span></span>
          </p>
        </div>

<div class="fieldset">
          <h1><span>Select Your Box(es)</span></h1>
          <p>
            <select data-placeholder="Choose your box(es)..." class="chosen-select" name="box_dstr[]" id="box_dstr" multiple required="required">
              <option value=""></option>
            </select>
            <span></span>
            <a style="margin-left: 12px;" href="javascript:void(0)" class="tooltip" title="Please select your boxes from the list. You can select a max of 20 boxes per submission.<br />.<br />You can select multiple boxes by holding the left ctrl on your keyboard and making your selection">Help</a>
          </p>
          <div class="noBdstrBoxes"></div>
        </div>

Open in new window

0
Comment
Question by:peter-cooper
  • 8
  • 5
14 Comments
 
LVL 9

Expert Comment

by:Shahzad Fateh Ali
ID: 40444203
Hi Peter,

Instead of using your own you can use http://www.appelsiini.net/projects/chained

Thanks
0
 
LVL 8

Expert Comment

by:Ahmed Merghani
ID: 40444209
You need to do that with AJAX. When the drop down list trigger a change, an AJAX call need to be happened to send the selected item from the list to server. At server, do your query based on selected item and send result back to client. Result can be well formatted html code for drop down 2. Or can be JSON format contains the OPTION and its VALUE. At the client using jQuery, you can place the result.
0
 

Author Comment

by:peter-cooper
ID: 40444218
@Ahmed do you have working example please. Thanks
0
 

Author Comment

by:peter-cooper
ID: 40444222
@Shahzad Thanks for link but I would rather try to find a solution based on my existing code rather than change it all. Thanks
0
 
LVL 9

Expert Comment

by:Shahzad Fateh Ali
ID: 40445387
For your code, what you can do is, have individual callback function for every dropdown which will be triggered on change.

These callback will hit different urls for fetching specific results based on the parameters passed. Here is a sample explanation.


var _callbacks = {
 // callback for getting dept on change of customer dropdown
 dept: function(){
  // Add loader, get depts for customer
  // when data received, add the data in dept select box and trigger change for that and remove loader
},
 address: function(){
  // Add loader, get address for dept
  // when data received, add the data in addresses select box and trigger change for that and remove loader
},
 boxes: function(){
 // Add loader, get boxes for address
  // when data received, add the data in boxes select box and remove loader
}
}

// attach events on select boxes when page loads
$(document).ready(function(){
   $('select#dstr_customer').on('change', _callbacks.dept);
   $('select#dstr_dept').on('change', _callbacks.address);
   $('select#dstr_address').on('change', _callbacks.boxes);
})

Open in new window

0
 

Author Comment

by:peter-cooper
ID: 40445521
@Shahzad

Thanks for that. However, I am not sure how to incorporate your code into mine. Could you please help with this. Also, I need to populate both the address select and the box select from the dept change event.  You have them as individual change events. Thanks
0
 

Author Comment

by:peter-cooper
ID: 40445534
I have managed to follow the logic, but get 'ReferenceError: _callbacks is not defined' when the page loads. Here is a sample of code which i put together. Where have I gone wrong? Thanks

$(function() {
var _callbacks = {
 // callback for getting dept on change of customer dropdown
 dept: function(){
  // Add loader, get depts for customer
  // when data received, add the data in dept select box and trigger change for that and remove loader
  
  $(this).after('<div id="loader"><imgages src="img/loading.gif" alt="loading files" /></div>');
    $.get('loadboxClientDstrsubcat.php?cltdstrdept=' + $(this).val(), function(data) {
      $("#dstr_dept").html(data);
      $('#loader').slideUp(200, function() {
        $(this).remove();
        $("#dstr_dept").trigger("chosen:updated");
      });
    });
},
 address: function(){
  // Add loader, get address for dept
  // when data received, add the data in addresses select box and trigger change for that and remove loader
},
 boxes: function(){
 // Add loader, get boxes for address
  // when data received, add the data in boxes select box and remove loader
}
}
});

// attach events on select boxes when page loads
$(function(){
   $('select#dstr_customer').on('change', _callbacks.dept);
   $('select#dstr_dept').on('change', _callbacks.address);
   $('select#dstr_address').on('change', _callbacks.boxes);
});

Open in new window

0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:peter-cooper
ID: 40445542
@Shahzad

For some weird reason, I put the callback function in doc ready. Removed and error gone.
0
 
LVL 9

Expert Comment

by:Shahzad Fateh Ali
ID: 40446698
Did the final version of your code work for you?
Did it resolve your original issue?
0
 

Author Comment

by:peter-cooper
ID: 40446782
@Shahzad

Also, I need to populate both the address select and the box select from the dept change event.  You have them as individual change events. Thanks

This is what I need to happen. Thanks
0
 
LVL 9

Expert Comment

by:Shahzad Fateh Ali
ID: 40446949
You will need to add your logic in the callback functions.
0
 

Author Comment

by:peter-cooper
ID: 40447006
Seems to me that I have to make 2 db calls from one change event. 1 for dept and 1 for address. Is that possible. Thanks
0
 
LVL 9

Accepted Solution

by:
Shahzad Fateh Ali earned 500 total points
ID: 40447025
Yes you can make 2 calls, but the alternative is that you get json object in your single call like
$.get('loadboxDstrsubcat.php?dstrdept=' + $(this).val(), function(data) {

      var json = JSON.parse(data);
      $("#box_dstr").html(data.boxes);
      $("#dstr_address").html(data.address);

});

Open in new window


In your php, your output will be

$response['boxes'] = HTML_FOR_BOXES_SELECT;
$response['address'] = HTML_FOR_ADDRESS_SELECT;

echo json_encode(response);

Open in new window

0
 

Author Closing Comment

by:peter-cooper
ID: 40447203
Thank you very much
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Introduction Got endorsements from your clients?  Great!  There is almost nothing better than word-of-mouth advertising.  But how can you do that on the internet?  Sure you can make a page for endorsement quotations and list them all, but who is …
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now