简体   繁体   中英

How to check if drop-down is selected in JavaScript

I have a validator function looping through to check and see if all inputs have been filled out, but I also need to check if the dropdown's have been selected as well. I would like to write that into the same function.

    function validateSave (){
        // reset status
       var good = true                                       
       $('.errormessage-left').removeClass('active-left')
       $('input').removeClass("warning")
       $('input').each(function(){
           if ($(this).val() == "") {
           console.log("found an empty");
           good = false
           $(this).addClass("warning")
           $('.errormessage-left').addClass('active-left'),
           $('.modal').addClass('modal-active'); 
        }
    })
    console.log(good)
    return good
    }

What's the best way to go about this?

您可以像输入元素一样在下拉菜单( <select>元素val()上使用val() ,因此只需将其包含在选择器中

$('input, select').each(function(){

You can do this :

Assuming the first element is :"please choose..."

if ($(".myDDL").get(0).selectedIndex>0)...

or

if ($(".myDDL").prop('selectedIndex')>0)...

you should be able to add this to your loop:

if ($(this).prop('type')=='select-one'){
   if ($(this).prop('selectedIndex')==0){
      console.log("found an empty");
      good = false
      $(this).addClass("warning")
      $('.errormessage-left').addClass('active-left'),
      $('.modal').addClass('modal-active'); 
   }
}

Try this:

$('input').each(function(){
           if($(this).prop('selected') == true){
              // selected item
           }
});

Assuming your HTML looks something like this:

<input type="text" name="whatever">
<select>
    <option value="">Choose One...</option>
    <option value="choice1">Choice 1</option>
    <option value="choice2">Choice 2</option>
    <option value="choice3">Choice 3</option>
</select>

Then your jQuery can figure it out like this

$('input, select').each(function(){
    if($(this).val() == ''){
        alert('Cannot be blank!');
    }
    else{
       //proceed
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM