Javascript:如何正确检查所选选项是否为空?

时间:2016-09-22 13:47:19

标签: javascript jquery arrays

我在这里选择了选项,我不知道为什么如果我没有选择任何选项意味着(-select-)values =“”没有值,仍然无效。我的选择选项是一个数组,因为它在循环中。

这是我的代码

var randomGender_arr = [];
var tae = true;
if(randGender == 'random'){
    $('select[name="randomGender[]"]').each(function(k,v){

        if($(v).val()===''){
            alert('Please select a gender')
        }else{
            randomGender_arr.push($(v).val());
        }

    });
}else{

}

顺便说一下,我选择的选项就在这里,因为你可以看到我的第一个选项被禁用了。怎么可能被认为是空的?并检查我何时离开选项中的一个(-select-)然后返回false。

echo'<div style="float:right; position:absolute; top:10px; right:0;">
<label for="randomGender">Gender:</label>
    <select name="randomGender[]" id="randomGender" class="form-control randomGender">
        <option disabled readonly selected>-select-</option>
        <option value="male">Male</option>
        <option value="female">Female</option>
    </select>
</div>
<div style="clear:both;"></div>';

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
let changeTime = 0;

let opt = document.querySelector(".opt");

let submit = document.querySelector(".submit");

let notif = document.querySelector(".notif");

opt.addEventListener("change",function(){
  changeTime++;
});

submit.addEventListener("click",function(){

  if(changeTime != 0){
    // Success
    notif.textContent = "Success";
    
  }else{
    notif.textContent = "Please chose at less one time!";
  }
  
});
&#13;
<div class="opt" style="float:right; position:absolute; top:10px; right:0;">
<label for="randomGender">Gender:</label>
    <select name="randomGender[]" id="randomGender" class="form-control randomGender">
        <option disabled readonly selected>-select-</option>
        <option value="male">Male</option>
        <option value="female">Female</option>
    </select>
</div>
<div style="clear:both;"></div>
<button class="submit">Button</button>
<p class="notif"></p>
&#13;
&#13;
&#13;