JQuery - object.id undefined when it should not be

I work with jQuery and I come across this strange (or possibly stupid) error.

In my HTML, I:

<input type="password" name="repeatPassword" id="id_repeatPassword" /> 

And then in my javascript code I have:

validateRepeatPassword($('#id_repeatPassword'));

Unfortunately, in the function "validateRepeatPassword":

function validateRepeatPassword(o) {
        // this works
        if (o.value == $("#id_password").val()) {
        // this returns "undefined"
        alert(o.id)
...
}

why?

+5
source share
2 answers

o is a reference to a jQuery object, not a reference to a DOM element. Inside your validateRepeatPassword function, do:

alert( $(o).attr('id') );

If you want to access the direct property of a DOM element from a jQuery object,

alert( o[0].id )

alert( o.get(0).id );
+13
source

There ois a jQuery object inside your function , you must capture the id using the attr function o.

alert(o.attr('id'));

DOM validateRepeatPassword, :

validateRepeatPassword($('#id_repeatPassword').get(0));
+2

All Articles