简体   繁体   中英

Renaming form fields added or deleted dynamically

I'm looking for help to rename the name attributes of some fields created dynamically. Now, my code assigns new values to the added fields (it increments according to the length of the div) but the problem appears when I delete a field, I don't know how to rename the remaining according to the number of fields deleted.

jQuery:

$(document).ready(function () {
    $("#add").click(function () {
        var intId = $("#reglas div").length;
        var fieldWrapper = $('<div></div>', {
            class: 'fieldwrapper',
            id: 'field' + intId
        });
        var fPath = $('<input align="left" type="text" placeholder="Path" class="reglas_wrapper" id="path" name="field1_' + intId + '" required /> ');
        var fTTL = $('<input type="text" class="reglas_wrapper" placeholder="TTL" id="ttl" name="field2_' + intId + '" required />');
        var removeButton = $('<input align="right" type="button" id="del" class="remove" value="-" /> <br><br>');
        removeButton.click(function () {
            $(this).parent().remove();
        });
        fieldWrapper.append(fPath);
        fieldWrapper.append(fTTL);
        fieldWrapper.append(removeButton);
        $("#reglas").append(fieldWrapper);

    });
    $("#cache").each(function () {
        $(this).qtip({
            content: {
                text: $(this).next('.tooltiptext')
            }
        });
    });

});
$('#formsite').on('submit', function (e) {
    //prevent the default submithandling
    e.preventDefault();
    //send the data of 'this' (the matched form) to yourURL
    $.post('siteform.php', $(this).serialize());
});

HERE'S MY FULL CODE: http://jsfiddle.net/34rYv/131/

You will want an incrementor. Check out this updated fiddle .

Here is the beginning of the code:

$(document).ready(function() {
    var myIncr = 0;
    $("#add").click(function() {
        myIncr++;
        var intId = myIncr;

You can add a class or id to each input field, and then depending on that class or id add the name as

<input type="text" class="something" />

Use this jQuery:

var classval = $('input[type=text]').attr('class'); // get class..
// now add the name as
$(this).attr('name', classval);

You can have as many inputs, they will be added the name depending on their class or id!

So even if the input fields are deleted, you will still have the class attributes in the control!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM