Jquery check for duplicate dropdown values

2019-08-08 15:07发布

问题:

I'm trying to do prevent a user from having the same value in two drop down menus. Jquery is returning true regardless of the values selected.

$("select[id$='go']").change(function() {
    var value = $(this);
    $("select[id$='go']").each(function() {
        if ($(this).val() === value.val()) {
            $('#work').html("DUBS");
        }
    });
});

<select id="_go">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

<select id="_gogo">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

<div id="work"></div>

http://jsfiddle.net/zbaKE/1/

Is there a proper way to do this?

回答1:

You need to remove the DUBS text on false, and also not test the same select field. Use not() to achieve this.

Demo: http://jsfiddle.net/zbaKE/3/

$("select[id$='go']").change(function() {
   var value = $(this).val();
   $("select[id$='go']").not(this).each(function() {
       if ($(this).val() == value) {
           $('#work').html("DUBS");
       }else{
           $("#work").html("SUBS");
       }
   });
});​


回答2:

If you want to prevent user to select same value from other dropdown, you may use something like this;

var $select = $("select[id$='go']");
$select.change(function() {
    $select
      .not(this)
      .find('option')
      .prop('disabled', '')
      .filter('[value='+this.value+']')
      .prop('disabled','disabled');
});
$select.eq(0).trigger('change');

working case is here (.not(), .find(), .prop(), .filter())



回答3:

I don't think it's returning true every time, your logic just doesn't remove the DUBS text if false.

Demo: http://jsfiddle.net/zbaKE/2/

$("select[id$='go']").change(function() {
    var value = $(this);
    $("select[id$='go']").each(function() {
        if ($(this).val() === value.val()) {
            $('#work').html("DUBS");
        } else {
            $('#work').html("");
        }
    });
});​


回答4:

The DUBS text isn't set back to empty before each change

Your jQuery could be written simply like this

$("select[id$='go']").change(function(){
    $('#work').html('Different');
    if ($("select[id=_go]").val() == $("select[id=_gogo]").val()){
        $('#work').html("Same");
    }
});

Here is a working example: http://jsfiddle.net/tuC4Y/1/