0

I have a string as

var selected_values = '1#2#3#4#5';

Now these are all values for <option>, which are separated by # (so final selected values would be 1 2 3 4 5), I need to select only those "options" whose value is mentioned in above string

How can I achieve this? 1. I need to split string 2. select only those options whose values are mentioned

For single value I am using following code

        var selObj = document.getElementById('list1');
        len = selObj.length;
        selected_value = '1';

        for (i = 0; i < len; i++) {
            if (selObj[i].value == selected_value) {
                selObj[i].selected = true;
            }
        }
2
  • Where's the jQuery? This is pure JS. Commented Mar 25, 2011 at 6:01
  • I need solution in JS or jQuery Commented Mar 25, 2011 at 6:04

1 Answer 1

1

Here's an example of the following →

You just need to split('#') on the selected values and then iterate over that array:

var selObj = document.getElementById('list1'),
    len = selObj.length,
    selected_values = '1#3#5',
    selected_array = selected_values.split('#'),
    alen = selected_array.length;

for (var i = 0; i < len; i++) {
    for (var j = 0; j < alen; j++) {
        if (selObj[i].value == selected_array[j]) {
            selObj[i].selected = true;
        }
    }
}
Sign up to request clarification or add additional context in comments.

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.