crackedcornjimmy
crackedcornjimmy

Reputation: 1992

Data attribute undefined

I have a textbox and a checkbox:

<input type="text" id="tb1" onFocus="CheckboxDisable('cb1');" />
<input type="checkbox" id="cb1" data-ieflub=""/>

When the textbox comes into focus, I would like to disable the checkbox and set the data attribute ieflub to a value. My code is the following:

function CheckboxDisable(id){
    document.getElementById(id).disabled = true;

    $('#id').attr('ieflub', 'yes');
}

As you can see, quite simple. Except, it doesn't work.

I traced through this, using Firebug and see that $('#id').data('data-ieflub'); is undefined inside the CheckboxDisable function.

Why?

Upvotes: 2

Views: 1090

Answers (2)

dfsq
dfsq

Reputation: 193261

You are passing some undeclared (looks like) variable cb1, while based on how you are using it in CheckboxDisable function, you want to pass the string cb1:

<input type="text" id="tb1" onFocus="CheckboxDisable('cb1');" />
<input type="checkbox" id="cb1" data-ieflub=""/>

Also in the function you need to construct selector with variable:

function CheckboxDisable(id) {
    document.getElementById(id).disabled = true;
    $('#' + id).data('ieflub', 'yes');
}

Note, that there is a convenient method to deal with data-attributes $.fn.data. Of course you could also go with attr method, but in this case you should have used full attribute name .attr('data-ieflub', 'yes'). With data method, prefix data- should be dropped.

Finally, it makes sense to use jQuery fully and change from

document.getElementById(id).disabled = true;

to $() method. The final function after additional optimization will become:

function CheckboxDisable(id) {
    $('#' + id).prop('disabled', true).data('ieflub', 'yes');
}

New methods used:

  • $.fn.prop to get/set DOM element properties, like disabled, checked, etc.
  • $.fn.data to get/set data properties, read data-attributes.

Upvotes: 4

fzzfzzfzz
fzzfzzfzz

Reputation: 1248

The '#id' in $('#id').attr('ieflub', 'yes'); is an ordinary string - it isn't getting replaced by '#cb1' as you might like. Try $('#' + id).attr('ieflub', 'yes'); instead.

There's also a problem in your html - replace onFocus="CheckboxDisable(cb1);" with onFocus="CheckboxDisable('cb1');" - you want to pass the string of the id, not a variable called cb1.

Upvotes: 0

Related Questions