X'Byte X'Byte - 7 months ago 16
Javascript Question

Get value from html button attribute

I have the following likert scale:

<div class="btn-toolbar" role="toolbar" aria-label="...">
<div class="btn-group" role="group" aria-label="...">
<a class="btn btn-link disabled" disabled style="width:10px">Not<br />Fearsome</a>
<button id="fear1" type="button" name="gender" class="btn btn-default likert-1" val="0">1</button>
<button id="fear2" type="button" name="gender" class="btn btn-default likert-2" val="1">2</button>
<button id="fear3" type="button" name="gender" class="btn btn-default likert-3" val="2">3</button>
<button id="fear4" type="button" name="gender" class="btn btn-default likert-4" val="3">4</button>
<button id="fear5" type="button" name="gender" class="btn btn-default likert-5" val="4">5</button>
<a class="btn btn-link disabled" disabled style="width:10px">Extremely<br />Fearsome</a>
</div>
</div>


I am trying to access the 'val' attribute from a script by using:

$('#fear').val($(this).getAttribute('val'));


but this does not seem to work.

Note:
#fear
is the
id
of a hidden variable

Answer

getAttribute is a standard DOM method but you are trying to call it on a jQuery object.

Either use a standard DOM object:

this.getAttribute('val')

or use the jQuery attr method:

$(this).attr('val')

Note that val is not a valid attribute for the button element. Consider data-val instead.

Alternative, avoid adding an extra attribute with redundant information in the first place.

$(this).text();