Reputation: 161
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
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.
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
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