最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamically add and remove <input> jQuery - Stack Overflow

programmeradmin1浏览0评论

So I have the following HTML. The idea is that by default the user can input 2 teams, but they should have an option to add more. My add New Team function works perfectly -

what I am trying to do is allow the user to remove the inputs that they add. So they can

I'm kind of struggling how to append a "remove" button and the jQuery for that.

Here is a jsFiddle /

All help much appreciated!

 <div class="control-group">
    <div id="teamArea"class="controls">
      <input type="text" name="teamName[]">
      <input type="text" name="teamName[]">
    </div>
   <a id="addNewTeam">Add another</a>
 </div>


 $("#addNewTeam").click(function(e) {
    //Append new field
    e.preventDefault();
    var newField = $('#teamArea input:first').clone();
    newField.val("");
    $("#teamArea").append(newField);
  });

So I have the following HTML. The idea is that by default the user can input 2 teams, but they should have an option to add more. My add New Team function works perfectly -

what I am trying to do is allow the user to remove the inputs that they add. So they can

I'm kind of struggling how to append a "remove" button and the jQuery for that.

Here is a jsFiddle http://jsfiddle/sqn9Y/

All help much appreciated!

 <div class="control-group">
    <div id="teamArea"class="controls">
      <input type="text" name="teamName[]">
      <input type="text" name="teamName[]">
    </div>
   <a id="addNewTeam">Add another</a>
 </div>


 $("#addNewTeam").click(function(e) {
    //Append new field
    e.preventDefault();
    var newField = $('#teamArea input:first').clone();
    newField.val("");
    $("#teamArea").append(newField);
  });
Share Improve this question edited Dec 5, 2013 at 10:29 Kevin Bowersox 94.5k19 gold badges163 silver badges197 bronze badges asked Dec 5, 2013 at 10:18 user2656127user2656127 6653 gold badges15 silver badges31 bronze badges 3
  • Are you thinking of adding a single "remove" button that removes the last input? Can the user remove all inputs or do you want a minimum of two? – nnnnnn Commented Dec 5, 2013 at 10:25
  • So I think perhaps a single Remove button that removes the last input could be the best way? And yes, there should always be a minimum of two. – user2656127 Commented Dec 5, 2013 at 10:26
  • "could be the best way?" - Well the other option is a button next to each input so that the user can remove them in any order. If you went that way I'd say it's not a problem if the user removes them all - they can always add them back and you can have some validation on submit to ensure they've got at least two. – nnnnnn Commented Dec 5, 2013 at 10:27
Add a ment  | 

6 Answers 6

Reset to default 5

Here is a basic example to get your started:

$("#addNewTeam").click(function(){
    var elem = $("<input/>",{
        type: "text",
        name: "teamName[]"
    });

    var removeLink = $("<span/>").html("X").click(function(){
        $(elem).remove();
        $(this).remove();
    });

    $("#teamArea").append(elem).append(removeLink);
});

JS Fiddle: http://jsfiddle/at6f9/

Add a remove link to delete the lastly added element. Refer the below link

http://jsfiddle/sqn9Y/4/

$("#remove").click(function(e){
if($('#teamArea input').length>1) {//remove all except one
     $('#teamArea input:last').remove();
}
});

check the below fiddle

http://jsfiddle/sqn9Y/3/

$("#addRemoveTeam").click(function(e) {

   e.preventDefault();
   var newField = $('#tag_' + tagCount);
   tagCount--;
  newField.remove();
});

This would remove the last one.Similarly if u want to remove all the inputs just run it in a loop.Hope this helps. enter code here This would remove the last one.Similarly if u want to remove all the inputs just run it in a loop.Hope this helps.

<div class="control-group">
<div id="teamArea"class="controls">
<input type="text" name="teamName[]">
<input type="text" name="teamName[]">
</div>
<a id="addNewTeam">Add another</a>
<a id="removeNewTeam">Add another</a>
</div>

$("#addNewTeam").click(function(e) {
//Append new field
e.preventDefault();
var newField = $('#teamArea input:first').clone();
newField.val("");
$("#teamArea").append(newField);
});
$("#removeNewTeam").click(function(e) {
var currentChildren=$("#teamArea").children();
var currentChidlrenLength=currentChildren.length;
$("#teamArea").children()[currentChidlrenLength-1].remove()
});

There are a few things I'm not clear on about what you want. Do you want the remove button at the bottom with the add button? Do you want only one remove button for all newly added input fields?

Assuming the answer to both of those questions is 'yes' AND that you want the remove button to remove the inputs in the reverse order they were added, the simplest idea I can think of is to hide/show the remove button.

The example code (including your code) would be:

HTML

 <div class="control-group">
    <div id="teamArea"class="controls">
      <input type="text" name="teamName[]">
      <input type="text" name="teamName[]">
    </div>
   <a id="addNewTeam">Add another</a>
   <a id="removeLastTeam" style="display:none;">Remove Last</a>

JavaScript

$("#addNewTeam").click(function(e) {
    //Append new field
    e.preventDefault();
    var newField = $('#teamArea input:first').clone();
    newField.val("");
    $("#teamArea").append(newField);
  });

$('#removeLastTeam').click(function() {
    if ($('div.controls').find('input').length > 2)
    {
        $("#teamArea input:last-child").remove();
    }
});

$('.control-group').click(function(e) {

    if ($('div.controls').find('input').length > 2)
    {
        $('#removeLastTeam').show();
    }
});

 </div>

I'd like to expand on Kevins awesomely succinct example above, say for instance that you wanted to limit the amount of input fields a user could add. You can add a simple counter to help you achieve your goal.

In my example, I was building a form that would allow users to add multiple input names if they had more than one dog.

    var counter = 0
    jQuery(function () {
      $(".newDog").click(function(){
        counter ++;
        if (counter < 4) {
          var elem = $("<input/>",{
            type: "text",
            name: `dogname${counter}`
        });
        } else {
          alert("You can only add 4 Dog Names")
        }
        
        var removeLink = $("<span/>").html("X").click(function(){
            $(elem).remove();
            $(this).remove();
            counter --;
        });
        
        $(".dogname-inputs").append(elem).append(removeLink);
    });
    })

Full credit as mentioned to https://stackoverflow./users/714969/kevin-bowersox

发布评论

评论列表(0)

  1. 暂无评论