Paengski
Paengski

Reputation: 349

Accessing the array values of dropdownbox using JQuery

<select size="6" name="operator[]" id="operator[]" size="5" multiple="">
    <option value="1" >One</option>
    <option value="2" >Two</option>
    ....
    ....
    <option value="10" >Ten</option>
</select>

My question now is how can I access the array values of dropdownbox using jquery?

$("#operator").val(); // Not working
$("#operator[]").val(); // Not working as well

Upvotes: 0

Views: 125

Answers (5)

Clyde Lobo
Clyde Lobo

Reputation: 9174

You will have to escape the [ and ] using \\

$("#operator\\[\\]").val();

or you can use $("select[id='operator[]']").val()

Demo

Upvotes: 0

Riz
Riz

Reputation: 10246

$("select[name='operator[]']").val();

Example: http://jsbin.com/eqoyes/1/edit

Upvotes: 1

webdeveloper
webdeveloper

Reputation: 17288

This is not valid id and name property, use this code:

$("#operator").find('option:selected').each(function(){
    alert(this.value);
});

demo: jsfiddle.net/VYjEM/

Upvotes: 1

Nikola Petkanski
Nikola Petkanski

Reputation: 4794

First things first. I think it is not allowed to use an array for element id. With that being said, set the element id to 'operator' rather than 'operator[]'.

After you've done that, you can get the options in several ways:

  1. Using the element dom id:

    $('#operator option');
    
  2. Using the element dom type:

    $('select option');
    
  3. Using both (recommended):

    $('select#operator option');
    

More information about the selectors jQuery supports can be found at the official website.

Upvotes: 0

Jon
Jon

Reputation: 437336

The syntax $("select").val() will give you the values of the selected options. If you want to get hold of all the options, use $("select > option").

Also: using the characters [] in the id attribute is illegal in HTML 4 and it does not buy you anything particular; you should probably fix that.

Upvotes: 0

Related Questions