I have an issue with the code below, I'm using onclick attribute to call the function below, then checking for which type of data-attr is passed. then assigning it to a local variable outside the function. but some how it saves 1 attr and displays it on alert and show the other one as undefined and then when I click on the other attr it shows it and for the first one says undefined. my js and HTML below.
jQuery code:
<script>
var attr1 = null;
var attr2 = null;
function createLink(sportAttr) {
if($(sportAttr).attr("data-provider-sport-id") != typeof undefined && $(sportAttr).attr("data-provider-sport-id") !== false) {
attr2 = $(sportAttr).attr("data-provider-sport-id");
//alert(attr2);
}
if($(sportAttr).attr("data-main-sport-id") != typeof undefined && $(sportAttr).attr("data-main-sport-id") !== false) {
attr1 = $(sportAttr).attr("data-main-sport-id");
//alert(attr1);
}
alert(attr1 + " and second attr is " + attr2);
//it never reaches the next line because for some reason one of the attrs is always null
if(attr1 != null && attr2 != null) {
if(confirm("Are you sure you want to create this link")) {
}
}
}
</script>
HTML code:
<i data-provider-sport-id="9" onclick="createLink(this)">Music</i>
<b data-main-sport-id="17" onclick="createLink(this)">Music</b>
when I click on the first one it displays "undefined and second attr is 9".
when I click on the second one it displays "17 and second attr is undefined"
any clues?