Reputation: 17387
I'm very unexperienced jQuery programmer unable to find a bug in my trivial script. Could you please help?
I want to emphasize a checkbox if its state differs from the initial value. That initial value is stored as data-init
attribute. The generated html for checked and unchecked input looks like this:
<td><input checked data-init id="controls-0-modeU" name="controls-0-modeU" type="checkbox" value="y"></td>
<td><input id="controls-1-modeU" name="controls-1-modeU" type="checkbox" value="y"></td>
In the accepted answer here: Retrieve boolean data from data attribute in jquery there is: "The jQuery .data()
method is smart about recognizing boolean and numeric values and converts them into their native type". That is what I want.
My script begins with:
$(document).ready(function(){
$("td input:checkbox").change(function(){
var $init = $(this).data("init")
But the value of $init
is either undefined
(for initially unchecked input) or an empty string (for initially checked). Both of them evaluate to false. Why am I not getting true/false instead?
Upvotes: 1
Views: 987
Reputation: 97727
A data attribute is not treated like a boolean attribute by jQuery(like checked, readonly, etc) so you have to give it a value
<td><input checked data-init="true" id="controls-0-modeU" name="controls-0-modeU" type="checkbox" value="y"></td>
<td><input data-init="false" id="controls-1-modeU" name="controls-1-modeU" type="checkbox" value="y"></td>
if you want to keep your mark up you'll have to do the heavy lifting yourself
var $init = $(this).is("[data-init]");
Upvotes: 3
Reputation: 1480
you can check if the element has the attribute like so:
if (!!$(this).attr("data-init")) {
// its there
}
else {
// its not
}
Upvotes: 0