1

I have two dropdown i want when i select for example from dropdown test1 option with value a

the second dropdown test2 show only the options that have value a

  <select name="test1" id="test1" onchange="document.getElementById('test2').value=this.value">
   <option value="Select">Select</option>
   <option value="a">a</option>
   <option value="b">b</option>
   <option value="c">c</option>
</select>


<select id="test2" name="test2">
<option value="Select">Select</option>
   <option value="a">a</option>
   <option value="a">b</option>
   <option value="a">c</option>
   <option value="b">1</option>
   <option value="b">2</option>
   <option value="b">3</option>
   <option value="c">c</option>
 </select>
JackNew
  • 95
  • 2
  • 11
  • 1
    You really don't want to do it this way . . . each option should have a unique value. You could use the values from "test1" as a prefix for the values in "test2" (e.g., "aa", "ab", "ac", "b1", "b2", etc.) , but each value should be unique. – talemyn Dec 10 '13 at 22:25
  • i know that each value should be unique but just want to know how its done for html purpose only – JackNew Dec 10 '13 at 22:27
  • possible duplicate of [How to populate a cascading Dropdown with JQuery](http://stackoverflow.com/questions/18351921/how-to-populate-a-cascading-dropdown-with-jquery) – Daveo Dec 10 '13 at 22:33

3 Answers3

1

Or you can go this way:

jQuery(document).ready(function($){
    var options = $('#test2 option');
    $('#test1').on('change', function(e){
        $('#test2').append(options);
        $('#test2 option[value!=' + $(this).val() +']').remove();
    });
});

fiddle

waldek_h
  • 930
  • 9
  • 16
0

Since you've tagged this with JQuery, if I were to not alter your HTML at all, you could do this by changing the JS in your onchange from this:

document.getElementById('test2').value=this.value

. . . to this:

$("test2").find("option").hide();
$("test2").find("[value^='" + $("test1").val() + "']").show();

That would hid all of the options in the "test2" dropdown, and then show all of the ones that have a value that starts with the value of the currently selected "test1" option.

Note: this will also work if you chose to update the code to only use the "test1" values as a prefix for the "test2" values. ;)

UPDATE: Fixed a typo in the code.

talemyn
  • 7,822
  • 4
  • 31
  • 52
0

Like it was said, you really don't want to do it this way as each option should have a unique value....but here is one way to accomplish it: jsFiddle

Using jQuery, you could check for the value of the selected option in test1, hide all those in test2 that don't match then show those with a matching value.

$('#test1').on('change', function() {
    $('#test2 option:not(option[value='+$(this).val()+'])').hide();
    $('#test2 option[value='+$(this).val()+']').show();
});
Brian
  • 1,184
  • 2
  • 21
  • 38