简体   繁体   中英

Adding, deleting jquery fields

Help, I have a function that changes the index, I would like the fields to be added to a new div and the last div deleted.

 const addActivity = (parent, name) => { const el = $(parent).find(`input[name^="${name}"]`).last(); const attr = el.attr('name'); const index = +attr.match(/(?<=\[).+?(?=\])/)[0]; const newEl = el.clone(); newEl.attr('name', `${name}[${index + 1}]`); $(parent).append(newEl); $(parent).append('<input type="button" class="btnRemove" value="Remove"/>'); } $('.addField').click(() => { addActivity('div', 'phoneNumber'); }); $(document).on('click', '.btnRemove', function() { $(this).parent().remove(); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form name="test"> <div class="formRow"> <input type="text" name="phoneNumber[0]" /> </div> <a href="javascript:void(0);" class="addField">Add [+]</a> </form>

You dont need index's, its already there since you have the name="phoneNumber[]" as array.

Try:

const addActivity = (parent, name) => {
    const firstRow = $(parent).first();
    const lastRow = $(parent).last();
    const newRow = firstRow.clone()
    newRow.find('input').val('');
    newRow.append('<input type="button" class="btnRemove" value="Remove"/>');
    lastRow.after(newRow);
}

dont forget to chane the name="phoneNumber[]"

<input type="text" name="phoneNumber[]" />

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