2

From here Are empty HTML5 data attributes valid?

They said that data attribute can be property

So I use this to test, this expected result is true / false, but I only got undefined, how to get the correct result using jquery?

<input type='checkbox' onclick='testDataProp(this)' data-tf>
<input type='checkbox' onclick='testDataProp(this)'>
function testDataProp(clickedBox)
{
    var trueFalse=$(clickedBox).prop('data-tf');
    alert(trueFalse);
}
Community
  • 1
  • 1
CL So
  • 3,647
  • 10
  • 51
  • 95

1 Answers1

4

use .data() to get data attributes, as:

function testDataProp(clickedBox)
{
    var trueFalse=$(clickedBox).data('tf');
    alert(trueFalse);
}

Demo jsFiddle

Update: you could use .hasData() to check, as:

function testDataProp(clickedBox)
{
    var trueFalse=$.hasData(clickedBox); //returns false
    alert(trueFalse);
}

If you want to check if data-tf attribute exists then you could use .hasAttribute():

function testDataProp(clickedBox)
{
    var trueFalse=$(clickedBox)[0].hasAttribute('data-tf'); //returns true for first and false for second checkbox
    alert(trueFalse);
}
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162