views:

91

answers:

3

I have some input checkboxes that are being dynamically generated in a $.post callback function. Then i have a $().change() call that does things when the value is changed (alerts some info). However, for the dynamically generated inputs, the .change() does not work. There are other inputs that work that are hardcoded into the html that work, but the other ones do not.

Here is the code.

<html>
<head>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script>
    $(document).ready(function(){
     $("#hideme").hide();
     $.post("php/test.php",{},function(data){
      writeMe = "<input type='checkbox' name='foo' value='" + data + "'>" + data;
      $("#insert").html(writeMe);
     }, "json");
     $("input[name=foo]").change(function(){
      alert($(this).attr("value"));
     })
    });
    </script>

</head>
<body>
    <div id="insert"></div>
    <input type="checkbox" name='foo' value='world'>world
</body>
</html>

php/test.php is simply:

echo json_encode("hello");
+1  A: 

immediately after posting this question, i tried putting the .change() INSIDE the callback and everything worked out nicely.

$.post("php/test.php",{},function(data){
    writeMe = "<input type='checkbox' name='foo' value='" + data + "'>" + data;
    $("#insert").html(writeMe);

    $("input[name=foo]").change(function(){
        alert($(this).attr("value"));
    });
}, "json");
contagious
Yup. Basically the .post(...) function creates an asynchronous call to "php/test.php". The callback function doesn't execute until the data comes back, at which time your change event had already been bound to the existing inputs.
Joel Potter
+2  A: 

The problem is that your statement:

$("input[name=foo]").change(function(){
     alert($(this).attr("value"));
})

doesn't have any effect because at the time it executes, there are no elements that match $("input[name=foo]") because the $.post() callback hasn't happened yet.

slacy
+2  A: 

In addition, if you do need to define the hooks before the $.post takes place, look at using LiveQuery, as it allows you to listen for any new elements that match your selector and bind them too.

Michael Heap
awesome, this is definitely another option
contagious
In addition .live() is available in jQuery 1.3.x which caters for this exact situation.
Julian