I need to get to newly created list elements , so I can loop through them on submit
.
Let's Start of with select
and empty ul
:
<select name="car" id="js_car_select">
<option value="1">BMW</option>
<option value="2">Audi</option>
</select>
<ul id="js_car_list"></ul>
and some basic jQuery:
// Append car name to the list on select change
$('#js_car_select').on('change', function() {
$('#js_car_list').append('<li>' + $(this).find('option:selected').text() + '</li>');
});
After this I have a list of cars as newly created elements.
How can I get to them on submit
? Now when I try, none of the new li
elements is available - $('#js_car_list li').length
= 0.
How and where should I listen to new elements creation?
EDIT:
The select
and ul
are part of the interface. On submit
I want to append the new list to a form as hidden input
s, so they can be serialized with the whole form.
You have to replace
$('#js_car_list').append('<li>' + $(this).text() + '</li>');
with
$('#js_car_list').append('<li>' + $(this).find('option:selected').text() + '</li>');
because $(this)
refers to <select>
element.
So, in order to append only the selected option, you have to target the selected one with option:selected
.
Check the DEMO
$('#js_car_select').on('change', function() {
$('#js_car_list').append('<li>' + $(this).find('option:selected').text() + '</li>');
});
$(document).on('click', '#submit', function() {
var list = [];
$('#js_car_list > li').each(function() {
list.push($(this).text());
});
// append the list items where ever you want ..
alert(list);
});
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.