Julia
Julia

Reputation: 161

When an input button field is added to the page using jQuery, how to access values

I have generated input button fields based on values inputted elsewhere in the page

 $('#saved_answers').prepend('<input type="button" name="remove_answer" value="' + answerstring + '"><br />');

Afterwards, I tried calling:

$("input:button[name=remove_answer]").click(function() {
  alert("Test!");
});

But nothing happens. When I view source, I also notice that none of the new code shows up. However, it does show up visually in the window.

Upvotes: 0

Views: 58

Answers (2)

Alistair Nelson
Alistair Nelson

Reputation: 3293

You should use the jQuery on method rather than click, so something like

    $('#saved_answers').on('click', 'some selector for your newly added button', function(){
        alert("Test!");
    }

This will allow for the event to be attached correctly.

See jQuery .on method


If you use this it should work:

<html>
<head>
</head>
<body>
    <div id="saved_answers"></div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
    $(function(){
    $('#saved_answers').prepend('<input type="button" name="remove_answer" value="test" />');
    $('#saved_answers').on('click', 'input:button[name=remove_answer]', function(){
        alert($(this).val());
    });
});
</script>
</body>
</html>

Upvotes: 1

zs2020
zs2020

Reputation: 54514

Correct me if I misunderstood your question. What you did is binding an event handler to the click event,

$("input:button[name=remove_answer]").click(function () {
    alert("Test!");
});

if you want to trigger the click event, you need this

$("input:button[name=remove_answer]").click();

Upvotes: 0

Related Questions