jQuery Question

Javascript : Check if multiple select dropdown has same value except the first selected option

I have multiple select option fields.

HTML

<select class="selectRound" name="criteriaRound[]" >
<option selected="true" disabled="true"> - select -</option>
<option value="16">value1</option>
<option value="17">value2</option>
<option value="18">value3</option>
<option value="19">value4</option>
</select>

<select class=" selectRound" name="criteriaRound[]">
<option selected="true" disabled="true"> - select -</option>
<option value="16">value1</option>
<option value="17">value2</option>
<option value="18">value3</option>
<option value="19">value4</option>
</select>

<select class=" selectRound" name="criteriaRound[]">
<option selected="true" disabled="true"> - select -</option>
<option value="16">value1</option>
<option value="17">value2</option>
<option value="18">value3</option>
<option value="19">value4</option>
</select>


And now I am trying to validate if each of those has same value. But how to avoid the first selected index in validation. Because what happen is if i choose an option at first time, the other remaining -select- field are still validating.

https://jsfiddle.net/uhhk8vd3/2/

JS

$(document).on('change','.selectRound', function(e){
var tralse = true;
var selectRound_arr = []; // for contestant name
$('.selectRound').each(function(k, v){
var getVal = $(v).val();
if($.trim(selectRound_arr.indexOf(getVal)) != -1){ //
tralse = false;
//it should be if value 1 = value 1 then alert
//But -select- = -select- are still keep validating, how to prevent this
alert('Contestant cannot be same name');
return false;
}else{
selectRound_arr.push($(v).val());
}

});
if(!tralse){
return false;
}
});

Answer

The updated fiddle is here https://jsfiddle.net/uhhk8vd3/3/

$(document).on('change', '.selectRound', function(e) {
  var tralse = true;
  var selectRound_arr = []; // for contestant name
  $('.selectRound').each(function(k, v) {
    var getVal = $(v).val();
    //alert(getVal);
    if (getVal && $.trim(selectRound_arr.indexOf(getVal)) != -1) {
      tralse = false;
      //it should be if value 1 = value 1 then alert, and not those if -select- = -select-. how to avoid those -select-
      alert('Contestant cannot be same name');
      $(v).val("");
      return false;
    } else {
      selectRound_arr.push($(v).val());
    }

  });
  if (!tralse) {
    return false;
  }
});
Comments