HTML
<form id = "form1">
<div class = "fields">
<div class="add">Add</div>
</div>
</form>
<form id = "form2">
<div class = "fields">
<div class="add">Add</div>
</div>
</form>
JS
$('.add').live('click', function() {
$('<input type="text" value="test">').appendTo('.fields');
})
I want add add input only to this form from where is clicked button not to both, how to limit insert ?
asked May 29, 2014 at 18:05
Wizard
11.4k38 gold badges100 silver badges167 bronze badges
2 Answers 2
Use closest() to get the form of the button and then append the input control.
like this:
$('.add').live('click', function() {
$(this).closest("form").append('<input type="text" value="test">');
})
answered May 29, 2014 at 18:09
Ehsan Sajjad
62.6k16 gold badges113 silver badges171 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
live is deprecated, use .on for event delegation. And if this form isn't dynamic, just use a handler and reference this:
$(".add").click(function() {
var input = $('<input type="text" value="test">');
$(this).parent(".fields").append(input);
});
answered May 29, 2014 at 18:07
tymeJV
105k14 gold badges165 silver badges158 bronze badges
2 Comments
Jay Blanchard
If the OP is using an older version of jQuery
on() will not be available.tymeJV
@JayBlanchard -- True - either way, if the form isn't dynamic there's no reason for
.on or .live :Dlang-js