I am working on the below demo. Why am I not able to pass the $("#sample")
into a function like below functions?
function GetAtts(elem) { var x = elem.data('x'); var y = elem.data('y'); console.log(x + ' ' + y); } function GetAttsThis(elem) { var x = this.data('x'); var y = this.data('y'); console.log(x + ' ' + y); } GetAtts('sample'); GetAtts('$("#sample")'); GetAttsThis('sample');
Here is the demo:
function GetAtts(elem) { var x = elem.data('x'); var y = elem.data('y'); console.log(x + ' ' + y); } function GetAttsThis(elem) { var x = this.data('x'); var y = this.data('y'); console.log(x + ' ' + y); } GetAtts('sample'); GetAtts('$("#sample")'); GetAttsThis('sample');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="sample" type="text" data-x="5" data-y="20">
As you can see I am getting:
Uncaught TypeError: elem.data is not a function
and:
Uncaught TypeError: this.data is not a function
on both formats of functions.
Advertisement
Answer
You’ve to pass the object like :
GetAtts($("#sample"));
The this
keyword doesn’t refer to the input since you’re using it without a specific context.
You could use the .apply()
method instead to set this
to $("#sample")
within the function’s scope, like :
GetAttsThis.apply($("#sample"));
function GetAtts(elem) { var x = elem.data('limitn'); var y = elem.data('limitp'); console.log(x + ' ' + y); } function GetAttsThis() { var x = this.data('limitn'); var y = this.data('limitp'); console.log(x + ' ' + y); } GetAtts($("#sample")); GetAttsThis.apply($("#sample"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="sample" type="text" data-limitn="5" data-limitp="20">