आनंद
आनंद

Reputation: 2582

Why can't we set the jquery selector object to another object's property and use them later?

In the following code, I'm trying to do set the jquery selector object to another object property but it's not working out. What am I getting wrong here?

index.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Page</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="javascript.js"></script>
</head>
<body>
    <p id="name"></p>
    <p id="password"></p>
</body>
</html>

javascript.js

var obj = {
    name:$('#name'),
    password:$('#password'),
    setval: function () {
        this.name.html("anand");
        this.password.html("abc@1234");
    }
};

$(document).ready(obj.setval());

Upvotes: 0

Views: 63

Answers (2)

Musa
Musa

Reputation: 97727

You're creating the object before the elements you try to select are created and also your document.ready code is wrong.
obj.setval() executes the function then passed its result to $(document).ready as a parameter, what you want to do is pass a function as the parameter, an anonymous function is usually the easiest.

Try

var obj;

$(document).ready(function(){
    obj = {
    name:$('#name'),
    password:$('#password'),
    setval: function () {
        this.name.html("anand");
        this.password.html("abc@1234");
        }
    };
    obj.setval()

});

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167250

This works. This is not the right way you invoke the function. The below is wrong:

$(document).ready(obj.setval());

You should use:

$(document).ready(function () {
  obj.setval();
});

Or, the other way is, in case you are not using objects with this keyword:

$(document).ready(obj.setval);

The function expects a function to be executed.

See the working snippet here:

var obj = {
  name:$('#name'),
  password:$('#password'),
  setval: function () {
    this.name.html("anand");
    this.password.html("abc@1234");
  }
};
$(document).ready(function () {
  obj.setval();
});
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<p id="name"></p>
<p id="password"></p>

Upvotes: 3

Related Questions