简体   繁体   中英

Fill second dropdown with the same value as the first dropdown

I have a dynamic number of dropdowns. When a value is selected in the first dropdown, the value of the second and so on dropdowns will be the same with the first dropdown. But the user has the option to change the value of the second and so on dropdowns , but not changing the first and other dropdown's value.

<select name="dropdown[]">
  <option value="1">Sony</option>
  <option value="2">Nintendo</option>
  <option value="3">Microsoft</option>
</select>

<select name="dropdown[]">
  <option value="1">Sony</option>
  <option value="2">Nintendo</option>
  <option value="3">Microsoft</option>
</select>

<select name="dropdown[]">
  <option value="1">Sony</option>
  <option value="2">Nintendo</option>
  <option value="3">Microsoft</option>
</select>

How can I achieve this using javascript or jquery libraries?

Use a change event and then alter the other dropdowns:

$("select[name=dropdown\\[\\]]").change(function() {
    var value = this.value;    
    $("select[name=dropdown\\[\\]]").not(this).val(value);
});

Demo: http://jsfiddle.net/awv14f6r/1/

If you want to change them in order (first alters the second, etc) - use next along with this

$(this).next("select").val(value);

You can attach a listener to the first select element:

var selects = document.querySelectorAll('select[name="dropdown[]"]');

selects[0].addEventListener('change', function () {
  for (var i = 0; i < selects.length; i++) {
    selects[i].value = selects[0].value;
  }
});

When the value of only the first select changes, it updates the values of the other selects. This way does not rely on any 3rd-party libraries.

Demo: http://jsfiddle.net/cuefb9ag/

var id = $('#DropDownID1 option:selected').val();
 var textValue = $('#DropDownID1 option:selected').text();
        $('#DropDownID2').prop('selectedIndex', 0);
        $('#DropDownID2').select2('data', {
            val: id,
            text: textValue
        });
        $('#DropDownID2 option:selected').val(id);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM