Reputation: 235
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
$("#2").attr({"data-sort-code":003});
function callfun()
{
var code=$("#2").data("sort-code");
$get('lblName').value=code;
alert(code);
}
</script>
<html>
<body>
<ul>
<li><a id="1" data-sort-code="001">Comapny 1</a>
<ul>
<li><a id="2" data-sort-code="001001"> Company 1.1</a>
</li>
<li><a id="3" data-sort-code="001002"> Company 1.1</a>
</li>
</ul>
</li>
<li> <a id="4" data-sort-code="002"></a>
</li>
</ul>
<input type="button" onclick="callfun();" value="Click" />
<input type="label" id="lblName"/>
</body>
</html>
<ul>
<li><a id="1" data-sort-code="001">Comapny 1</a>
<ul>
<li><a id="2" data-sort-code="001001"> Company 1.1</a>
</li>
<li><a id="3" data-sort-code="001002"> Company 1.1</a>
</li>
</ul>
</li>
<li> <a id="4" data-sort-code="002">Company 2</a>
</li>
</ul>
If i change the sort code of id=2 to 003 in runtime as follows,
$("#2").attr({"data-sort-code":003});
its changes at run time, but in the same run time if try to fetch the sort code as follows,
var code=$("#2").data("sort-code");
alert(code);
alert msg still shows as "001001"
can any one tell me how to get the sort code at run time.
Upvotes: 0
Views: 54
Reputation: 68423
check this fiddle
replace
$("#2").attr({"data-sort-code":003});
with
$("#2").attr("data-sort-code","003");
anyways 003
will become 3
unless enclosed in quotes
also check with
var code=$("#2").attr("data-sort-code");
alert(code);
Upvotes: 1
Reputation: 5622
If you are setting the data variable as
$("#2").attr({"data-sort-code":003});
than use:
code=$("#2").attr("data-sort-code");
alert(code);
and if you are using
var code=$("#2").data("sort-code");
alert(code);
than set it by using
$("#2").data("sort-code","003");
Upvotes: 0
Reputation: 8151
Below code will fix it. Just use data function in both the places. set it with
$("#2").data("sort-code","003");
and get it with
$("#2").data("sort-code")
Upvotes: 0