Question

I am quite new to jQuery and got a problem with finding the right select on the page. When I search for multiple select I get how to select a few options and its not what I need.

So basicly here is an example:

Html part:

<div id='select-zone'>
   <select class='nselect' id='1'>
       <option value='1'>test</option>
       <option value='2'>test2</option>
   </select>

   <select class='nselect' id='2'>
       <option value='1'>test</option>
       <option value='2'>test2</option>      
   </select>
</div>

So basically I want to get the id from the select using the class attribute 'nselect'.

Jquery:

$(document).ready(function() {
var id;
$("nselect").change(function() 
   id = $(this).attr('id');
});
});

I think that my problem is that I am not getting the right element with this. If you guys could guide me and tell me what I am doing wrong and if I am even accessing the right element with $(this) you would be a great life saver.

I made a code simplest possible.

Thanks a lot.

Was it helpful?

Solution

You're just missing the . off your class selector, and the opening curly brace off the callback function:

$(".nselect").change(function() {
// ^ missed this                ^ and this

   id = $(this).attr('id');
});

Side note: you could make your code a bit more efficient by just using the native id property, rather than creating a new jQuery object:

$(".nselect").change(function() {
   id = this.id;
});

OTHER TIPS

At first glance, as nselect is a class name, you'll need to use $(".nselect") rather than just $('nselect')

You have to use a dot to address classes

$(".nselect")

Also, I would use .blur() instead of .change()

Depending on where you want to use the id variable, I believe you'd want to put var id; before the $(document).ready...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top