eastboundr
eastboundr

Reputation: 1877

How come attr() gives me a strange result?

so I have:

<span selected="Y" onclick="change();">Click here to test~</span>


<script src="jquery-1.7.2.js"></script>

<script>
function change()
{
  $('span[selected=Y]').attr("selected","N");
}
</script>

When I clicked the span, and checked the attribute of the span using firebug, the attribute "selected" changed to "selected" instead of "N".

so the result is selected="selected" !!??

How come it did not change to selected="N"

Upvotes: 2

Views: 81

Answers (2)

Tim Down
Tim Down

Reputation: 324507

The reason is that for elements for which it is valid (<option> elements, for example), selected is a Boolean attribute, and the only valid value for a Boolean attribute is the name of the attribute itself. jQuery's attr() method is trying and failing to be clever and "correct" the value of your selected attribute.

Clearly jQuery doesn't handle invalid attributes correctly, which is somewhat understandable. Your options are either to use the getAttribute() method of the element itself (which will work in all major browsers), or better, use an attribute prefixed by data-, which is valid according to the HTML5 spec, supported by browsers and by jQuery.

Upvotes: 0

thecodeparadox
thecodeparadox

Reputation: 87073

selected is not valid attribute to span, instead of that you can use data.

<span data-selected="Y">Click here to test~</span>

jQuery

$('span[data-selected=Y]').on('click', function() {
  $(this).data('selected', 'N');
});

Read more about jQuery .data()

Upvotes: 4

Related Questions