0

I'm tryng to fix this function to show alert on dropdown. Where am I wrong? Alert does not appear.

JS:

<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function () {
    $( "#species" ).change(function(){
    if ( $(this).children(":selected").val() == "" ) {
    alert("empty");
    }
    });
});
});
</script>

FORM:

<form>
<label for="species" id="species">*Species:</label><br />
<select id="species" name="species" size="1">
<option value="">Please choose a species</option>
<option value="21">Chicken</option>
<option value="28">Turkey</option>
</select>
<br />
<input type="submit" id="submit" value="Validate!" />
</form>

2 Answers 2

1

You are having 2 events and the 2nd is being bound on the click event.

Perhaps you want something like this:

<script type="text/javascript">
$(document).ready(function(){
    $("#submit").click(function () {
    if ( $("#species" ).children(":selected").val() == "" ) {
       alert("empty");
    }
    });
});
});
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

A couple of things: 1. You have the same id for your label as you do for your select element which confuses jQuery.

  1. You bound your click event to the change event on the selectBox which is not necessary.

Try this:

$(document).ready(function(){
   $("#submit").click(function (e) {
       if($('#species').find(":selected").val()===""){
         alert("empty");
       }    
       e.preventDefault()
    });
});

http://jsfiddle.net/6SuvK/

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.