Mohamed Omezzine
Mohamed Omezzine

Reputation: 1104

caching dom element using namespace

Am trying to chache DOM using namespace but when I call I get "undefined" instead of jQuery object

  <form id="create_profile">  

      <input type="text" name="name"/>
      <input type="text" name="email" />
      <input type="text" name="password" />
      <input type="text" name="passwordconfirm" />

      <span onclick="profile.create()">valider</span>

 </form>

Js:

 var profile = {

  create: function(){

   alert(profileFields.test); // show done!
   alert(profileFields.create_form.attr('id')); // show undefined instead of create_profil

  }


}

var profileFields = {

        test: "done!",  
        create_form: $("#create_profile"),
        $email: $("input[name='name']", this.create_form),
        $password: $("input[name='pass']", this.create_form),
        $passwordconfirm: $("input[name='passconfirm']", this.create_form),
        $name: $("input[name='email']", this.create_form),
        $tel: $("input[name='tel']",this.create_form)  

}  

Upvotes: 0

Views: 72

Answers (2)

plalx
plalx

Reputation: 43728

You probably simply did not wait until the DOM was ready.

Wrap your code in:

$(function () {
    //your code
});

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074949

This tells us that your JavaScript code is running before that element exists, so $("#create_profile") returns an empty jQuery object. Calling attr on an empty jQuery object returns undefined. If your script tag is higher up in the HTML than the elements it refers to, the elements won't exist as of when the script runs.

Either

  1. Put the script tag at the very end of the HTML, just before the closing </body> tag, or

  2. Use jQuery's ready to hold up execution of your code until "DOM ready."

#1 is preferred unless you don't control where the script tag goes. More:

Upvotes: 1

Related Questions