-2

I have multiple select box on my page with id's drop_01, drop_02 and so on along with a common class.

I am writing a jQuery that whenever a select box is changed, I get the number of selected options for that select box. Following is the jQuery but its not working. Can anyone tell me what am i doing wrong.

var x = "drop_" + idnum; // (idnum contains the numeric index like 01,02 etc).
var length = $(' "#" + x option:selected').length;

But when i give the hard coded id like below, it works fine.

var length = $('#drop_02 option:selected').length;

Please help.

1 Answer 1

0

You aren't concatenating the string of the selector properly:

var length = $('#' + x + ' option:selected').length;

I would strongly suggest you use an editor with syntax highlighting as it makes it virtually impossible to miss errors like this.

5
  • Thanks Rory, I overlooked that one. Jan 30, 2015 at 17:05
  • Rory, Can you please tell me how can we use this dynamic id with radio button. In my case 1st time the radio button functionality doesn;t work as intended but after that it works fine. It gives me undefined the 1st time. var value = $('input:radio[name=drop_'+idnum+']:checked').val(); Jan 30, 2015 at 18:39
  • You're probably best to start a new question for that. Jan 30, 2015 at 18:51
  • It doesn't allow me to post a new question :( Jan 30, 2015 at 19:12
  • $('input:radio[name=input_'+ idnum +']').change(function () { alert("hello"); }); (idnum is the same as above 01,02 etc) When i first change the value of radio button the above jquery is not triggered and after that it works good. Any thoughts on this. Jan 30, 2015 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.