0

I have a select form that looks kind of like this:

<select multiple="multiple" id="id_color_id" name="color_id"">
<option value="1">Red</option>
<option value="2">Blue</option>
<option value="3">Brown</option>
</select>

What I want to do is select the item above via javascript. This is actually part of a hidden form, so all I'm trying to do is leverage the serialize part of the form. I'm thinking it will just be easier to hack that after the serialize then to add this as well, but I also want to deselect any options that have already been selected.

So two questions:

  1. How to select an option via javascript. All I will know is "Red", "Blue" or "Brown". I also have a look up dictionary that can get me the values as well.

  2. How to deselect all options previous to selecting one of the above.

This is related to: Selecting options in a select via JQuery

3 Answers 3

2

Native Javascript:

var textToFind = 'Red';

var dd = document.getElementById('id_color_id');
for (var i = 0; i < dd.options.length; i++) {
    if (dd.options[i].text === textToFind) {
        dd.selectedIndex = i;
        break;
    }
}

or with jQuery:

$('#id_color_id option:contains('Blue')').prop('selected',true);

with variable:

var blue = "Blue";
$('#id_color_id option:contains(' + blue + ')').prop('selected',true);

And to deselect all selected options:

Native Javascript:

var elements = document.getElementById("id_color_id").options;

    for(var i = 0; i < elements.length; i++){
       if(elements[i].selected)
        elements[i].selected = false;
    }

jQuery:

$("#id_color_id option:selected").removeAttr("selected");
Sign up to request clarification or add additional context in comments.

2 Comments

In the example above, for jquery, how do you get the correct option if "blue" is a variable?
$('#id_color_id option:contains(' + blue + ')').prop('selected',true); Added to solution above.
0

To select an option by it's content (considering what you posted is what you have)

$("#id_color_id option:contains('Red')").prop('selected',true);

jsFiddle Demo

Comments

0

You can set the value on the select box using the .val() method. Running this will reset any previously selected values, so you don't need to do anything specific to accomplish that part. You can also use an array to select multiple values, which may be of interest, since you are using a multi select.

$("#id_color_id").val(['1','2']);

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.