7

I would like to be able to launch an alert message everytime the value of the dropdown is changed. I thought the code below should have worked but it is not for some unknow reason. Any ideas why?

Thanks.

<html>
<head>
<script type="text/javascript" src="lib/jquery.js"></script>
</head>
<body>

<script type="text/javascript">
    $("select").change(function(){
        alert(this.id);
    });
</script>


<select>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

</body>
</html>

3 Answers 3

13

The code is fine, you just aren't initialising it correctly.

Try....

$(document).ready(function() {
    $("select").change(function(){
        alert(this.id);
    });
});

see the documentation here.

Your function alerts the id of the select element (which you haven't assigned to anything anyway). I'm assuming you actually wanted to get the value from the dropdown? In which case you want:

alert($(this).val());
Sign up to request clarification or add additional context in comments.

Comments

3

Register the onchange handler once the DOM is ready on page load.

$(function() {

   $("select").change(function(event) {
        alert(this.id);
        // alert( $(this).attr('id') ); to get the id attr with jquery
    });

});

I would also suggest targeting the select element with an id. Your code will show an alert every time any select on the page is changed.

1 Comment

@Slaks: Ha, no problem. Not fussed who, just a bit baffled about why
0
$(document).ready(function(){
$("#projectsName").change(function(){
       alert("HI");
});

});

Please Note that projectName is the id of dropdown and there is no other id with the same name other wise jquery will not work also double check your jquery plugin

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.