Ben G
Ben G

Reputation: 26751

Why isn't jQuery binding with click?

Why isn't jQuery binding to the click event? When I click the selects, they don't alert, except for the one that I put onClick on.

<html>
<head>
<title>Robo</title>

<script type="text/javascript" src="jquery-1.4.2.min.js"></script><script type="text/javascript">

$('.changer').click(function(){alert('test');});


</script>
</head>
<body>

<select class="changer" name="dept" id="dept_select">
    <option value="">Select a Department</option>
</select>

<select onclick="alert('ya');" class="changer" name="course" id="course_select">
    <option value="">Select a Course</option>
</select>
<select class="changer" name="section" id="section_select">
    <option value="">Select a Section</option>
</select>

</body>
</html>

Upvotes: 0

Views: 124

Answers (5)

Joko Wandiro
Joko Wandiro

Reputation: 1987

You have to wrap syntax dg .ready handler.

<script type="text/javascript">
$(document).ready( function(){
   $('.changer').click(function(){alert('test');});
});
</script>

It's method used to specify a function to execute when the DOM is fully loaded.

Upvotes: 1

Vivek
Vivek

Reputation: 11028

you can also use delegate function...

$('.changer').delegate('click',function(){
   alert('test'); 
 });

Upvotes: 1

Kyle Trauberman
Kyle Trauberman

Reputation: 25684

Wrap your jQuery in a ready event:

$(function() {
    $('.changer').click(function(){alert('test');});
});

Upvotes: 1

Chandu
Chandu

Reputation: 82893

Because the .changer elements are not available in the dom when you are binding the click handlers. You can do two things:

Use jQuery ready event handler

 $.ready(function(){
      $('.changer').click(function(){
        alert('test');
      });
    });

or Use live function.

$('.changer').live("click", (function(){
   alert('test');
 });

Upvotes: 4

Sarfraz
Sarfraz

Reputation: 382616

You need to wrap your code in ready handler:

$(function(){
  $('.changer').click(function(){alert('test');});
});

Upvotes: 2

Related Questions