neilmarion
neilmarion

Reputation: 2382

Jquery Get Element by ID Problem

$(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

Upvotes: 1

Views: 5366

Answers (4)

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

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!

Upvotes: 3

Jeremy
Jeremy

Reputation: 4975

$('#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

Upvotes: 1

Zebra
Zebra

Reputation: 4006

try this:

alert( $('#new_school').attr('id') )

Upvotes: 1

kleinohad
kleinohad

Reputation: 5912

change this: alert($('#new_school').id) to this: alert($('#new_school').attr('id'))

Upvotes: 12

Related Questions