views:

149

answers:

2

Please have a look at this code -

When I click on myLink I get a modal dialog window which shows the html as defined below. This html includes a button (id=test_button), and when I click on this button I want to do an ajax request. But its not working. So to test it I am just doing an alert but it wont work as well.

Also will it be possible to update existing dom element values (just populate a form) from within a test_button click function.

Thanks for your help.

$('#myLink').click(function(event) {
 event.preventDefault();
 $('<div id="iContainer">Test: <input type="text" value="" id="test_text" /> 
  <input type="button" id="test_button" value="click" /></div>').appendTo('body');  
 $("#iContainer").dialog({     
  width: 600,
  modal: true,
  close: function(event, ui) {
   $("#iContainer").remove();
   }
  });
 });
 $('#test_button').click(function() {
  alert('I am in Alert');
  //alert($('#test_text').val());
 });
+2  A: 

Try with Events/live:

$('#test_button').live("click", function(){
  alert('test');
});
CMS
brilliant .. works .. let me test it again. thanks
Wbdvlpr
+1  A: 

The problem is that you're attempting to attach the click handler before the element exists.

As stated by CMS, you can either use .live() or you can add the click handler in your $('#myLink').click() function

Like so:

$('#myLink').click(function(event) {
        event.preventDefault();
        $('<div id="iContainer">Test: <input type="text" value="" id="test_text" /> 
                <input type="button" id="test_button" value="click" /></div>').appendTo('body');                
        $("#iContainer").dialog({                                       
                width: 600,
                modal: true,
                close: function(event, ui) {
                        $("#iContainer").remove();
                        }
                });

        $('#test_button').click(function() {
                alert('I am in Alert');
                //alert($('#test_text').val());
        });
});
Marc
how do I add it to $('#myLink').click() ?? thanks.
Wbdvlpr
ah I see. Cool
Wbdvlpr
See the code in the answer, I simply dragged the closing curly brace and paren down to enclose your $('#test_button').click(..) code. Just a note, I would think about separating these into something more modular, but this or CMS's solution will get you up and running.
Marc
yes, checked it.
Wbdvlpr