简体   繁体   中英

Adding Input Field to form

I was trying to use this:

Fiddle

But it seems that the jQuery version he is using is quite outdated.

However, the only necessary update I see in his code is to change .live() to .on() . But the remove button refused to work if I changed so.

    $('#remScnt').on('click', function() { 
            if( i > 2 ) {
                    $(this).parents('p').remove();
                    i--;
            }
            return false;
    });

Anyone has any idea why?

  1. The ID must be unique (This is not causing the trouble though)
  2. Delegation is needed for newly added content.

jQuery

$(function () {
    var scntDiv = $('.p_scents');
    var i = $('.p_scents p').length + 1;

    $('#addScnt').on('click', function () {
        $('<p><label for="p_scnts"><input type="text" class="p_scnt" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> <a href="#" class="remScnt">Remove</a></p>').appendTo(scntDiv);
        i++;
        return false;
    });

    $('.p_scents').on('click', '.remScnt', function () {
        if (i > 2) {
            $(this).parents('p').remove();
            i--;
        }
        return false;
    });
});

HTML

<h2><a href="#" id="addScnt">Add Another Input Box</a></h2>

<div class="p_scents">
    <p>
        <label for="p_scnts">
            <input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" />
        </label>
    </p>
</div>

This works perfectly: http://jsfiddle.net/uFkPx/

Looks like it needs a rewrite, several deprecated methods, dynamic elements created from strings, targeting all parents(), same ID's etc :

$(function () {
    var scntDiv = $('#p_scents'),
        i       = $('#p_scents p').length + 1;

    $('#addScnt').on('click', function (e) {
        e.preventDefault();
        var p = $('<p />'),
            l = $('<label />', {for: 'inp_'+i}),
            j = $('<input />', {type: 'text', 
                                id: 'inp_'+i, 
                                size: 20,
                                name: 'p_scnt_' + i,
                                placeholder: 'Input Value'
                               }),
            a = $('<a />', {href : '#', 
                            id: 'remScnt_' + i,
                            'class' : 'remScnt',
                            text: 'Remove'
                           });

        p.append(l.append(j), a).appendTo(scntDiv);
        i++;
    });

    scntDiv.on('click', '.remScnt', function (e) {
        e.preventDefault();
        if (i > 2) {
            $(this).closest('p').remove();
            i--;
        }
    });
});

FIDDLE

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