Reputation: 208
Ultimately my goal is to move one div next to the other, so what I was doing is to save the html in a variable and use the function "after" from jquery to place it in the correct location. It worked except for the fact that the content of the textbox (the one the user has to write) was not copied together with the rest.
I then tried to access to the html directly and even if I write something in the textbox I don't get it in the html.
var totalHtml = $("div#my-div-1").html()
However, I can access to the content of the textbox if I write:
$("div#my-div-1 input[type=text]").value
So why I cannot get it when I call the html? and how can I copy the whole html with the content of that input (and other inputs)?
Upvotes: 0
Views: 73
Reputation: 6378
Try a clone with the first parameter, 'withDataAndEvents' set to true. https://api.jquery.com/clone/
$('#copy').on('click', function() {
let original = $('.div1').first(),
myCopy = original.clone(true),
originalSelects = original.find('select'),
myCopySelects = myCopy.find('select');
myCopySelects.each(function(i, obj) {
$(obj).val(originalSelects.eq(i).val());
});
$('body').append(myCopy);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div1">
<p>Paragraph text here...</p>
<input>
<select>
<option selected="selected" value="1">One</option>
<option value="2" >Two</option>
<option value="3">Three</option>
</select>
<select>
<option value="1">One</option>
<option selected="selected" value="2" >Two</option>
<option value="3">Three</option>
</select>
</div>
<p>
<button id="copy">Copy</button>
</p>
Upvotes: 2
Reputation: 3660
The following works using the insertAfter jquery method. It moves the div with the child input alongwith its current input value
<div id="mydiv1">
<input type="text" value="hello">
</div>
<div id="mydiv2">another div</div>
<input id="mybtn" type="button" value="Do It">
With the following javascript
$(function(){
setTimeout(function(){
$('#mydiv1').insertAfter('#mydiv2');
}, 2000);
})
Upvotes: 0