Sydnal
Sydnal

Reputation: 3

Jquery Mulitple select field error

I have multiple select field each with multiple options. So, by using jquery to get the respective selected options content, I would be able to get the selected option content. However, this work for the first select field. But, does not work for others. Others keep referencing the first select field selected options content, instead of it owns. Please guide me! Thanks!

My Select fields

<select id="resource_dd" name="resource_dd">
    <option selected="selected" value="nil1">No resources.</option>
    <option value="1">Week1</option>
    <option value="2">Resource1</option>
</select>


<select id="module_dd" name="module_dd">
    <option selected="selected" value="nil2">No restriction.</option>
    <option value="1">IT1234</option>
    <option value="2">IT2345</option>
</select>

Jquery to retrieve the selected content.

$("#module_dd").change(function ( event ) {
    var option = $("this").children();
    var module_id = $(option+":selected").val(); //module_id get 'nil1' as content instead of nil2

});

Upvotes: 0

Views: 154

Answers (5)

ayyp
ayyp

Reputation: 6598

Please see Eli Courtwright's answer, but in addition to that, you should do something like $("select") or $("#module_dd, #resource_dd") to target both select fields.

Upvotes: 0

JAAulde
JAAulde

Reputation: 19550

Problem code

var option = $("this").children();
var module_id = $(option+":selected").val();

You can't concat a selector string to a jQ collection object. You need to filter the option collection for those which are selected either by:

var option = $( this ).children(":selected");

Or

var option = $( this ).children();
var module_id = option.filter(":selected").val();

Upvotes: 0

ShankarSangoli
ShankarSangoli

Reputation: 69905

Just try this, it will give you the selected value.

$("#module_dd").change(function ( event ) {
  var module_id = $(this).val(); 
});

Upvotes: 2

Eli Courtwright
Eli Courtwright

Reputation: 192891

First of all, you should be saying $(this) instead of $("this").

Second, $(event.target) is probably more appropriate here.

Third, using .children as in $(event.target).children(":selected") will get you what you want.

Upvotes: 1

Jason Gennaro
Jason Gennaro

Reputation: 34855

This is happening because you are referencing $("#module_dd").

You need to add another function and change that to $("#resource_dd") to get the other select field.

Upvotes: 0

Related Questions