The running code can be found here: http://jsfiddle.net/rwdengmz/
I apologise as i cant explain clearly my problem but here goes. eg: as i click on parent 1, it properly shows the value it exists in the child which is
This works fine however, the problem lies when i change parent option to example,Parent 2. It will then show yet again the proper child values
HOWEVER, before opening the dropdown it will show the previous child value and for this instance, it will show the child 1 from parent 1.
How do i make it that will just show purely the specific child values of the selected parent option?
<select id="parent">
<option value="1">Parent 1</option>
<option value="2">Parent 2</option>
<option value="3">Parent 3</option>
</select>
<select id="child">
<option data-parentid="1">Child 1 from Parent 1</option>
<option data-parentid="1">Child 2 from Parent 1</option>
<option data-parentid="2">Child 1 from Parent 2</option>
<option data-parentid="2">Child 2 from Parent 2</option>
<option data-parentid="3">Child 1 from Parent 3</option>
<option data-parentid="3">Child 2 from Parent 3</option>
</select>
$("#parent").on("change", function()
{
var id = $(this).val();
$("#child option").each(function()
{
$(this).css("display", ($(this).data("parentid") == id ? "" : "none"));
});
}).trigger("change");
All you need to do is set the attr
as selected
. This should help you solve the issue where the previous value is still being displayed despite the change
function called and the option being populated as desired.
$("#parent").on("change", function(){
$('#child option').filter(function(){
if($(this).data('parentid') == $('#parent').val()) {
$(this).show().attr('selected','true');
}
else {
$(this).hide();
}
});
});
Check out the FIDDLE
Try this code
$("#parent").on("change", function()
{
var id = $(this).val();
$("#child").children('option').hide();
$("select#child option[data-parentid="+id+"]").show().prop("selected", true);
}).trigger('change');