1

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;
}
});
1
  • set a value="" or value="select" for the default select and if the selected option value is not null then check for your condition. Commented Sep 3, 2016 at 7:14

1 Answer 1

2

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;
  }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.