Clone jquery element changing id then use keyup () not working
Problem: when I clone
<div id="#cloneme1">...</div>I get
<div id="cloneme2">...</div>, but the .keyup () function will not read the new DOM elements
$('#btnAdd').click(function() {
var num= $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum= new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it ID using newNum value
var newElem = $('#cloneme' + num).clone().attr('id', 'cloneme' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children(':first').attr('id', 'alteredguianswer' + newNum)
// insert the new element after the last "duplicatable" input field
$('#cloneme' + num).after(newElem);
});
$('input[type="text"]').keyup(function(){
var id = $(this).attr("id"); // variable id = id of current textfield
var value=$(this).val(); // variable value = value in current textfield
$("#someplace"+id).text(value); // edit text elsewhere on page using value
});
<div>
<input type="button" id="btnAdd" value="add another name" />
</div>
<div id="cloneme1" style="margin-bottom:4px;" class="clonedInput">Question:<input type="text" id="guianswer1" value="Answer 1" /></div>
I do not understand how to get a function to read new cloned elements
0
2 answers
You are attaching a keyup event for all relevant elements in the DOM, but not in future elements.
If you are using jQuery 1.7 or later, try using
$('input[type="text"]').on('keyup', function(){
var id = $(this).attr("id"); // variable id = id of current textfield
var value=$(this).val(); // variable value = value in current textfield
$("#someplace"+id).text(value); // edit text elsewhere on page using value
});
If you are using an earlier version, try using live
$('input[type="text"]').live('keyup', function(){
var id = $(this).attr("id"); // variable id = id of current textfield
var value=$(this).val(); // variable value = value in current textfield
$("#someplace"+id).text(value); // edit text elsewhere on page using value
});
+1