I Like
I Like

Reputation: 1847

create array using each class name

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! html

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

Answers (2)

Tushar
Tushar

Reputation: 87203

Two Problems:

  1. The 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.
  2. Syntax Errors highlighted in the code below

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

Ibrahim Khan
Ibrahim Khan

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

Related Questions