$(function() {
$(".form_new td select").change(function() {
alert($('#new_school').id)
});
});
I have the code above in my app. But It keeps on alerting "undefined." What am I doing wrong? #new_school is a textfield. I have already installed jquery. In my public/javascripts folder I have jquery.js, jquery.min.js and jquery.ujs.js. I am using Rails 3.0.9
$(function() {
$(".form_new td select").change(function() {
alert($('#new_school').id)
});
});
I have the code above in my app. But It keeps on alerting "undefined." What am I doing wrong? #new_school is a textfield. I have already installed jquery. In my public/javascripts folder I have jquery.js, jquery.min.js and jquery.ujs.js. I am using Rails 3.0.9
Share Improve this question asked Jul 31, 2011 at 5:18 neilmarionneilmarion 2,3827 gold badges21 silver badges36 bronze badges 1- can you post your relevant html? – Petar Ivanov Commented Jul 31, 2011 at 5:21
4 Answers
Reset to default 12change this: alert($('#new_school').id)
to this: alert($('#new_school').attr('id'))
Why it happens:
In $('#new_school').id
,
$('#new_school')
returns a Array
of elements, and id
is not defined in the Array
.
So it will throws you a undefined
.
How do you solve it:
$('#new_school')
[0]
.getAttribute('id')
, or$('#new_school').attr('id')
(.attr
will only find theid
of the first element in the array, read here.)$('#new_school')
[0]
.id
PS:
PS.: In your script: alert($('#new_school').id)
↑
The id
you finding is right there, duh!
try this:
alert( $('#new_school').attr('id') )
$('#new_school').attr('id') should work but this is useless because you have to know the id beforehand to select the element.
Usually you only do some like this
var currentId = $(this).attr('id');
to get the ID of the object that invoked the event