Reputation: 1847
I'm trying to create an array by accessing a class called 'name'. However, I'm only able to get the list of names in one block when I alert the array. I think I may be using the .each() wrong. I want to return an array that has the names listed separately. I would greatly appreciate any help!
jquery
$('.dropdown-content ul li span').click(function(){
$('.hiddenfield').val($(this).html());
$('form').submit(function(){
var arr=[];
$('.name').each( function()
arr.push(('.dropdown-content').val($(this).text()));
alert(arr);
})
});
});
Upvotes: 0
Views: 1015
Reputation: 87203
Two Problems:
submit
event handler should not be nested inside the click
handler. This will bind a new submit
event on the form each time <li>
is clicked.Code:
$('.dropdown-content ul li span').click(function () {
$('.hiddenfield').val($(this).html());
});
$('form').submit(function () {
var arr = [];
$('.name').each(function () { // <-- Missed { here
arr.push($('.dropdown-content').val($(this).text()));
// ^ Missed `$` here
alert(arr);
});
});
To get the array of text, you can use $.map
with $.get
.
var arr = $('.name').map(function () {
return $.trim($(this).text()); // Use trim to remove leading and trailing spaces
}).get();
Upvotes: 1
Reputation: 20740
You can do it like following using map()
function. Separate the click
and submit
event.
$('form').submit(function(){
var arr=[];
var arr = $('.name').map( function()
return $(this).text();
}).get();
alert(arr);
});
$('.dropdown-content ul li span').click(function() {
$('.hiddenfield').val($(this).html());
});
Upvotes: 1