Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery sets multiple dropdown options to selected

I have run into an interesting little problem that is probably just me being silly.

I have a select box that looks a little like this:

<select id="dom_" name="dom_">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    ...

The options represent days of the month and go up to 31.

Now, I was trying to select a default value when the a form with information is loaded (for editing), but I couldn't get it to work quite right.

I tried using this snippet I found in some previous SO questions:

$("#dom_ option[value$='" + 2 + "']").attr('selected', true);

This line runs and it sets the 2nd option to selected, but it also sets other 2X or X2 options to selected as well. For example, 12 and 22 will also be set to selected.

If however, I use this:

$("#dom_ option").each(function()
{
    if ($(this).val() == 2)
    {
        $(this).attr('selected', true);
    }
    else
    {
        $(this).attr('selected', false);
    }

});

Then the right option will get selected, but the SELECT box will not be updated.

I have to manually call $("#dom_").val(2); afterwords to update the box.

So, my question is, why does the first option not work and why does the second one not auto refresh?

Also, what exactly is the difference between taking a SELECT object via $("#dom_") and calling .val on it versus taking an option and setting selected to true? Do both of these send back the same POST or GET data?

Here is a jsFiddle that hopefully demonstrates this.

If it helps, I am using JQuery 1.6.4 but I could reproduce the same problem on some newer versions in jsFiddle.

I apologize if this question is too simple. I am still quite an amateur when it comes to JavaScript and JQuery.

like image 864
zermy Avatar asked Feb 25 '13 20:02

zermy


People also ask

What is multi select dropdown?

Multi select dropdown list is used when a user wants to store multiple values for the same record, whereas dropdown list is used to store a single value for a record. You can create custom categories of either dropdown list or multi select dropdown list and define items in each category.


1 Answers

You are using the ends with ($=), instead just use value= which will only match exactly the value you want.

$("#dom_ option[value='" + 2 + "']").attr('selected', true);
like image 199
Nix Avatar answered Sep 21 '22 19:09

Nix