0

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 ?

2 Answers 2

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">');

 })
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

If the OP is using an older version of jQuery on() will not be available.
@JayBlanchard -- True - either way, if the form isn't dynamic there's no reason for .on or .live :D

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.