0

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 Answers 2

2

Try with Events/live:

$('#test_button').live("click", function(){
  alert('test');
});
Sign up to request clarification or add additional context in comments.

Comments

1

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());
        });
});

1 Comment

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.

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.