0

I have multiple select dropdowns as such:

<select name="offer1cards[]">
    <option value="1">Card 1</option>
    <option value="2">Card 2</option>
    <option value="3">Card 3</option>
</select>
<select name="offer1cards[]">
    <option value="1">Card 1</option>
    <option value="2">Card 2</option>
    <option value="3">Card 3</option>
</select>
<select name="offer1cards[]">
    <option value="1">Card 1</option>
    <option value="2">Card 2</option>
    <option value="3">Card 3</option>
</select>

I am trying to get the values into a comma separated string using jquery but I know I am not doing something right:

var values = new Array();
$.each($("input[name='offer1cards[]']:selected"), function() {
    values.push($(this).val());
    var items = values.split(',');
    alert(items);
});

How can I get these values into a string?

2 Answers 2

1

You are unnecessarily using :selected and instead of split use join to join a array, Just do

var values = new Array(), var items;
$.each($("input[name='offer1cards[]']"), function() {
    values.push($(this).val());
});
items = values.join(',');
alert(items);
Sign up to request clarification or add additional context in comments.

1 Comment

This worked great, thanks! I just needed to change input to select for it to work.
1

You $.map() them and then .join() 'em.

var res = $.map($("select[name='offer1cards[]']"), function(ele) {
        return $(ele).val();
    }).join(', ');

    alert(res);

Demo: http://jsfiddle.net/5t9ddd98/1/

Comments

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.