Reputation: 430
I practicing jQuery, I came into a scenario which requires me to get the element name that is dynamically added inside the #field
div. my code below is working on static elements but not those elements that is manipulated dynamically.
//This works on static elements
$('#field').find('input, select, textarea').each( function() {
var name = $(this).attr('name');
});
I also tried:
1.
$('#field').get(0).find('input, select, textarea').each(function() {
var name = $(this).attr('name');
});
$('#field').find('input, select, textarea').each(document, function() {
var name = $(this).attr('name');
});
$('#field').find('input, select, textarea').get[0].each(function() {
var name = $(this).attr('name');
});
$(document, '#field').find('input, select, textarea').each(function() {
var name = $(this).attr('name');
});
PS: no.4 works but some elements outside the div is displayed. I want only those element inside #field div. the attempt no.1 - no.3 is not working.
Upvotes: 0
Views: 384
Reputation: 910
How about onchange event? you need to have a change event that care about changes on your input elements, also I made a button to change dynamically one of the elemtns, now whenever you change them, statically or dynamically all of them will change.
Important note
you need to trigger change()
event wherever you are dynamically change your inputs, look at js section that I called .change()
method.
$('input, select, textarea').on('change', function() {
$('#field').find('input, select, textarea').each( function() {
var name = $(this).attr('name');
$(this).val(name);
});
});
function myclick(){
// first let's change one of them dynamically
$("#thisone").val("hello").change();
return;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="field">
<input name="saeid" value="nothing">
<input id="thisone" name="Hdog" value="nothing">
<input name="jack" value="nothing">
<input name="maz" value="nothing">
<input name="banana" value="nothing">
</div>
<input name="banana" value="nothing">
<input name="banana" value="nothing">
<input name="banana" value="nothing">
<input type="button" onclick="myclick();" value="chane one of them and update all of them">
Upvotes: 1