freshtar
freshtar

Reputation: 11

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?

Upvotes: 1

Views: 2718

Answers (5)

Snowburnt
Snowburnt

Reputation: 6922

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'); 
   }
}

Upvotes: 0

MonkeyZeus
MonkeyZeus

Reputation: 20737

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
    }
}

Upvotes: 0

Ringo
Ringo

Reputation: 3965

Try this:

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

Upvotes: 0

Travis J
Travis J

Reputation: 82267

You can use val() on a dropdown (<select> element) just like an input element, so just include it in your selector

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

Upvotes: 1

Royi Namir
Royi Namir

Reputation: 148524

You can do this :

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

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

or

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

Upvotes: 0

Related Questions