0

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);
            })
    });
    });
3
  • Please post real code.... not images of code. How is anyone supposed to be able to copy code from an image to try to help you? Commented Jan 25, 2016 at 13:57
  • 1
    Why is submit nested inside click? Commented Jan 25, 2016 at 13:57
  • Missing $ in arr.push(('.dropdown-content') Commented Jan 25, 2016 at 13:59

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much! Can you explain what .get() does in this case?
Welcome @st4rgut. get() return an array from jQuery object.
1

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());
});

1 Comment

returns a jQuery object not an array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.