remove & add select box option if other selection changes

人盡茶涼 提交于 2019-12-02 11:19:11

Updated to an improved solution!

I hope this helps, it's a very basic demo and needs a few adjustments but should do the trick! http://jsfiddle.net/BUuZv/2/

If I understand you correctly, you have <option> elements with the same value in each <select> and you want to disable selection in the each of the other <select> elements when one of the <option> elements is selected. Here's a small snippet showing how I did that:

HTML

<select class="hello">
    <option value=""></option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="A">A</option>
</select>
<select class="hello">
    <option value=""></option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="B">B</option>
</select>
<select class="hello">
    <option value=""></option>    
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="C">C</option>
</select>

jQuery

$(document).ready(function () {
    $('select.hello').change(function () {
        $('select.hello option').attr('disabled', false);
        $('select.hello').each(function() {
            var val = $(this).find('option:selected').val();
            if (!val) return;
            $('select.hello option').filter(function() {
                return $(this).val() == val;
            }).attr('disabled', 'disabled');
        });
    });
});

And here is a link to the jsFiddle: http://jsfiddle.net/yLCVf/1/

I have updated the code. This is what you are looking for

$('select').change(function() {
  if ($(this).val() == 'other') {
    $('#select1, #select2, #select3').not(this)
      .children('option[value="other"]')
      .remove()
  } else {
    if ($('#select1, #select2, #select3').not(this).find('option[value=other]').length > 0) {

    } else {

      ($('#select1, #select2, #select3').not(this)
        .append('<option value="other">Other</option>'))
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select1" name="select1">
  <option>No Match</option>
  <option value="1">Test</option>
  <option value="2">Test 2</option>
  <option value="other">Other</option>
</select>

<select id="select2" name="select2">
  <option>No Match</option>
  <option value="1">Test</option>
  <option value="2">Test 2</option>
  <option value="other">Other</option>
</select>
<select id="select3" name="select3">
  <option>No Match</option>
  <option value="1">Test</option>
  <option value="2">Test 2</option>
  <option value="other">Other</option>
</select>

http://jsfiddle.net/dZqEu/2003/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!