samjhana joshi
samjhana joshi

Reputation: 2015

how to relate 2 dropdown and load data in 2nd dropdown in relation to 1st

I have two dropdown, one for division and another for products.According to division I want to load data in Products.i.e.instead of loading each and every products in dropdown I want to load products related to division selected.

<select name="Division" id="division">
<option value='1'>Div1</option>
<option value='2'>Div3</option>
<option value='3'>Div3</option>
<option value='4'>Div4</option>
</select>
<select name="Products" id="product">
<option value='<?php echo $pid ?>' rel='1'>Prod1</option>
<option value='<?php echo $pid ?>' rel='1'>Prod2</option>
<option value='<?php echo $pid ?>' rel='2'>Prod3</option>
<option value='<?php echo $pid ?>' rel='3'>Prod4</option>
<option value='<?php echo $pid ?>' rel='3'>Prod5</option>
<option value='<?php echo $pid ?>' rel='3'>Prod6</option>
</select>

Is there any way to do using PHP and jquery.Thanks for any help/suggestions.

Upvotes: 0

Views: 225

Answers (2)

Jurijs Kastanovs
Jurijs Kastanovs

Reputation: 685

You can add onChange event that would post the data back to backend and get the values for the 2nd dropdown.

Something like

$('#division').change(function(){
    $.post("myPhpScript.php",{"divisionId":$('#division').val()}, function(data){
         $.each(data, function(i, opt){
              var elem = $('<option/>', { value : opt["value"], html: opt["label"] });
              $('#product').append(elem);
         });
    }
});

And in php you get the JSONObject containing the value of the dropdown

{"divisionId":$('#division').val()}

and get your data according to that and return a JSONArray of JSONObjects that would contain new values.

[ { "value":"prod1", "label":"Product 1" }, { "value":"prod2", "label":"Product 2" } ]

Hope this helps you.

Upvotes: 1

E.K.
E.K.

Reputation: 21

Add an onchange Event to the first select field, which contains an Ajax Request to get the data for the new select field.

Another way would be hiding the not active select fields and show them when the onchange is triggered. This is more static.

Upvotes: 0

Related Questions