0

I have a multiple select dropdown. I am trying to show the selected values in the dropdown.

If I hard code the values, it works -

$("select[name=clause1]").val(["ab","cd"]);

but if I define a variable with the values, it does not -

var temp = "[\"ab\",\"cd\"]"; 
$("select[name=clause1]").val(temp);

what I am doing wrong?

0

2 Answers 2

1

The first snippet sets the values using an array. Second tries it with just a string. Since there is no matching value of that string, it simply doesn't set the value of the select box.

Change your code to this instead:

var temp = ["ab", "cd"]; 
$("select[name=clause1]").val(temp);

Additionally, if you've the string (JSON), you can convert it to the array using JSON.parse:

var temp = JSON.parse("[\"ab\",\"cd\"]"); 
$("select[name=clause1]").val(temp);
Sign up to request clarification or add additional context in comments.

Comments

0

You can also use eval function for this purpose.

var values= "[\"ab\",\"cd\"]"
$('select').val(eval(values))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple>
<option value="ab">ab</option>
<option value="bc">bc</option>
<option value="cd">cd</option>
</select>

However, eval is evil but worth useful in many cases. If you closely look into the link's description it will tell you the usage of JSON.parse using eval but in a safer manner.

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.