开发者

Add (and remove) group of textelements dynamically from a web form using javascript/jquery

im very new at javascipt (im php developer) so im really confused trying to get this working.

In my web form i have 3 textfields (name, description and year) that i need to let the user add as many he needs, clicking on a web lin开发者_如何学编程k, also, any new group of text fields need to have a new link on the side for removing it (remove me).

I tried some tutorial and some similar questions on stackoverflow but i dont get it well. If you can show me a code example just with this function i may understand the principle. Thanks for any help!


this is the simplest thing that has come to my mind, you can use it as a starting point:

HTML

<div class='container'>
    Name<input type='text' name='name[]'>
    Year<input type='text' name='year[]'>
    Description<input type='text' name='description[]'>
</div>
<button id='add'>Add</button>
<button id='remove'>Remove</button>

jQuery

function checkRemove() {
    if ($('div.container').length == 1) {
        $('#remove').hide();
    } else {
        $('#remove').show();
    }
};
$(document).ready(function() {
    checkRemove()
    $('#add').click(function() {
        $('div.container:last').after($('div.container:first').clone());
        checkRemove();
    });
    $('#remove').click(function() {
        $('div.container:last').remove();
        checkRemove();
    });
});

fiddle here: http://jsfiddle.net/Fc3ET/

In this way you take advantage of the fact that in PHP you can post arrays: server side you just have to iterate on $_POST['name'] to access the various submissions

EDIT - the following code is a different twist: you have a remove button for each group:

$(document).ready(function() {
    var removeButton = "<button id='remove'>Remove</button>";
    $('#add').click(function() {
        $('div.container:last').after($('div.container:first').clone());
        $('div.container:last').append(removeButton);

    });
    $('#remove').live('click', function() {
        $(this).closest('div.container').remove();
    });
});

Fiddle http://jsfiddle.net/Fc3ET/2/


jsFidde using append and live

String.format = function() {
    var s = arguments[0];
    for (var i = 0; i < arguments.length - 1; i++) {
        var reg = new RegExp("\\{" + i + "\\}", "gm");
        s = s.replace(reg, arguments[i + 1]);
    }

    return s;
}

var html = "<div>" + '<input name="name{0}" type="text" />' + '<input name="description{1}" type="text" />' + '<input name="year{2}" type="text" />' + '<input type="button" value="remove" class="remove" />' + '</div>',
    index = 0;

$(document).ready(function() {
    $('.adder').click(function() {
        addElements();
    })
    addElements();
    $('.remove').live('click', function() {
        $(this).parent().remove();
    })

});

function addElements() {
    $('#content').append(String.format(html, index, index, index));
    index = index + 1;
}


Look at this: http://jsfiddle.net/MkCtV/8/ (updated)

The only thing to remember, though, is that all your cloned form fields will have the same names. However, you can split those up and iterate through them server-side.

JavaScript:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
    $("#addnew").click(function(e) {
        $("#firstrow").clone() // copy the #firstrow
            .removeAttr("id")  // remove the duplicate ID
            .append('<a class="remover" href="#">Remove</a>') // add a "remove" link
            .insertAfter("#firstrow");  // add to the form
        e.preventDefault();
    });
    $(".remover").live("click",function(e) { 
        // .live() acts on .removers that aren't created yet
        $(this).parent().remove();  // remove the parent div
        e.preventDefault();
    });
});
</script>

HTML:

Add New Row
<form id="myform">
    <div id="firstrow">
    Name: <input type="text" name="name[]" size="5">
    Year: <input type="text" name="year[]" size="4">
    Description: <input type="text" name="desc[]" size="6">
    </div>
    <div>
        <input type="submit">
    </div>
</form>


Try enclosing them in a div element and then you can just remove the entire div.


Try this

Markup

<div class="inputFields">
   ..All the input fields here
</div>
<a href="javascript:void(0);" id="add">Add</a>

<div class="additionalFields">
</div>

JS

$("#add").click(function(){
   var $clone = $(".inputFields").clone(true);
   $clone.append($("<span>Remove</span").click(functio(){ 
        $(this).closest(".inputFields").remove();
   }));
   $(".additionalFields").append($clone);
});


There are 2 plugins you may consider:

  • jQuery Repeater
  • jquery.repeatable

This question has been posted almost 4 years ago. I just provide the info in case someone needs it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜