Accessing Value Of Inputs Within A Div In Each()
I have a bit of code that allows a user to add a new phone to a list like so const addPhone = async (phone) => { $('.phone-list').append(`
Solution 1:
You are .each()
ing the elements with arrow function, which doesn't have its own bindings to the this
keyword. Consider replacing it to normal function.
$(document).on('click', '#submit', async () => {
const phoneArray = [];
//—————————————————————vvvvvvvv——
$('.phone-div').each(function() {
console.log($(this).find('.type'));
console.log($(this).find('.detail'));
});
});
Solution 2:
It's probably because you're using arrow functions and this
doesn't refer to the element.
Either change your arrow function to a use function
keyword or use the second parameter of the each
callback to get the current element
in context:
$(document).on('click', '#submit', async () => {
const phoneArray = [];
$('.phone-div').each((index, element) => {
phoneArray.push({
type: $(element).find('.type').val(),
detail: $(element).find('.detail').val(),
})
});
});
Solution 3:
I don't know what you expected using async
. A "normal" function perfectly does the job.
And a fixed a couple typos in the .append()
...
functionaddPhone(phone){
$('.phone-list').append(`
<div class='phone-div'>
<table>
<tbody>
<tr>
<td>
<p>
<input class='type' type='text' value='${phone.type}'></input>
</p>
<p>
<input class='detail' type='text' value='${phone.detail}'></input>
</p>
</td>
</tr>
</tbody>
</table>
</div>
`);
}
$(document).on('click', '#submit', function(){
const phoneArray = [];
$('.phone-div').each(function(i){
console.log($(this).find('.type').val());
console.log($(this).find('.detail').val());
phoneArray.push({
type: $(this).find('.type').val(),
detail: $(this).find('.detail').val(),
})
});
console.log(phoneArray);
});
$("#add").on("click",function(){
// just for the demo... Since I can't know where this object comes from...var phone = {type:"cellular",detail:"1-888-555-5555"}
addPhone(phone);
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divclass="phone-list"></div><buttonid="add">Add</button><buttonid="submit">Submit</button>
Post a Comment for "Accessing Value Of Inputs Within A Div In Each()"