简体   繁体   中英

How to append jquery div to html correctly

I've got the input and button in div:

<div>
  <input id='input_id_0' value='name'>
  <button type="button" id="remove_id_0"></button>
</div>

I'd like to copy the input and the button, increase their id, wrap them in the div and attach after the previous one. So the result should be:

<div>
  <input id='input_id_0' value='name'>
  <button type="button" id="remove_id_0"></button>
</div>
<div>
  <input id='input_id_1' value='name'>
  <button type="button" id="remove_id_1"></button>
</div>

I wrote the code:

    cloneCount = 0;
    cloneCount += 1;
    var div = document.createElement('div');
    var previousInput = document.getElementById('input_id_' + (cloneCount-1))
    var newInput = $(previousInput)
         .clone(true)
         .attr('id', 'input_id_' + cloneCount)
    previousInput.append(newInput)

    var previousRemoveBtn = document.getElementById('remove_id_' + (cloneCount-1))
    var newRemoveBtn = $(previousRemoveBtn)
         .clone(true)
         .attr('id', 'remove_id_' + cloneCount)

   div.append(newInput)
   div.append(newRemoveBtn)

   $(previousInput).parent().after(div)

but that code results in text object[Object] object[Object] being appended to my original input. JSFiddle: https://jsfiddle.net/Malvinka87/z8t1sxcf/1/

Could you explain to me, please, why that is happening and how to fix it?

Since you're using jquery, you don't need to use document.getElementById or document.createElement like that. All of them can be done using jquery:

 var input = $('input').clone(); var input_id = input.prop('id'); input_id = input_id.substr(input_id.length - 1, 1); var button = $('button').clone(); var button_id = button.prop('id'); button_id = button_id.substr(button_id.length - 1, 1); input.prop('id', 'input_id_' + ++input_id); button.prop('id', 'remove_id_' + ++button_id); var div = $('<div>').append(input).append(button); div.insertAfter('div');
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <input id='input_id_0' value='name'> <button type="button" id="remove_id_0">btn</button> </div>

About the id, you can try to get the lastest character from the id string, then increasing it as a number before appending to the new element.

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