最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery Get Element by ID Problem - Stack Overflow

programmeradmin3浏览0评论
$(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
Add a ment  | 

4 Answers 4

Reset to default 12

change 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:

  1. $('#new_school')[0].getAttribute('id'), or
  2. $('#new_school').attr('id')
    (.attr will only find the id of the first element in the array, read here.)
  3. $('#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

发布评论

评论列表(0)

  1. 暂无评论