0

I have a simple multiple select which I am trying to send its selected values via ajax. I can use alert and it show the values selected to me but it goes through as blank in ajax. To test this, i tried to the replace and that doesn't work either. so there is something wrong and I can't figure it out!

<select id="multiple" multiple="multiple">
<option value="Text 1">Text 1</option>
<option value="Text 2">Text 2</option>
<option value="Text 3">Text 3</option>
</select>

If I choose options 2 and 3 the alert will show my selection like this:

var test = $("#multiple").val(); alert(test); will return: Text 2,Text 3

and if I use replace it doesn't work, IE:

test = test.replace(",", ", ");

I thought, this might be an array and tried to convert it to string and still it didn't work!

3
  • It is an array. What do you mean you tried to convert it to a string? Commented Mar 2, 2015 at 5:20
  • What do you mean by "it goes through as blank in ajax". Could you show the ajax code? Commented Mar 2, 2015 at 5:30
  • can you share the ajax request code... and have a look at your browser network tab(developer tools) to see what is the actual data that is being sent Commented Mar 2, 2015 at 5:34

1 Answer 1

1

Here test is an array so there is no array method called replace

instead you can use the .join() method like

test = test.join(", ");

Demo: Fiddle

.val()

In the case of select elements, it returns null when no option is selected and an array containing the value of each selected option when there is at least one and it is possible to select more because the multiple attribute is present.

When you call alert() and pass an array as you have done, the array will be converted to a string by calling the Array.toString() method, which will display each member of the array separated by coma(,)

Sign up to request clarification or add additional context in comments.

2 Comments

Judging from the question, this doesn't exactly solve the issue; it just explains that it's an array. The problem seems to be using that value in an AJAX request.
@Arun P Johny, this made it work and thank you for the explanation!

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.