Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery change event on dropdown

I just added the query lib to my web app and tested with simple alert:

<script src="<c:url value="/resources/jquery-1.10.2.min.js" />"></script>
<script type="text/javascript">
            $(function(){
                alert('jquery is working');
            }); 
</script>

And works fine. However when i want to implement an "change" event on my dropdown

<script src="<c:url value="/resources/jquery-1.10.2.min.js" />"></script>
<script type="text/javascript">
        $("#projectKey").change(function() {
            alert($('option:selected', $(this)).text());
        });
</script>

it displays me no alert, basically nothing is happening. My drop down is the following:

<select id="projectKey" name="projectKey">
    <option value="AM">AM</option>
    <option value="AIL">AIL</option>
    <option value="NEB">NEB</option>
    <option value="SSP">SSP</option>
</select>

Of course i tried to simplify the javascript, just o have

$("#projectKey").change(function() {
            alert("test");
});

but still no joy. It will be something with the selector or the drop down. Tried also "select#projectKey" but the result was of course the same. Any idea what i am doing wrong?

like image 287
shippi Avatar asked Jan 07 '14 16:01

shippi


1 Answers

You should've kept that DOM ready function

$(function() {
    $("#projectKey").change(function() {
        alert( $('option:selected', this).text() );
    });
});

The document isn't ready if you added the javascript before the elements in the DOM, you have to either use a DOM ready function or add the javascript after the elements, the usual place is right before the </body> tag

like image 153
adeneo Avatar answered Sep 20 '22 01:09

adeneo