我正在使用这样一组按钮:
<div class="btn-group">
<button type="button" class="btn btn-default" id="height_1" name="height" value="1" data-preview="preview_hl_height" onkeyup="validate()" onclick="validate()">14,5</button>
<button type="button" class="btn btn-default" id="height_2" name="height" value="2" data-preview="preview_hl_height" onkeyup="validate()" onclick="validate()">29,0</button>
<button type="button" class="btn btn-default" id="height_3" name="height" value="3" data-preview="preview_hl_height" onkeyup="validate()" onclick="validate()">43,5</button>
<button type="button" class="btn btn-default" id="height_4" name="height" value="4" data-preview="preview_hl_height" onkeyup="validate()" onclick="validate()">58,0</button>
<button type="button" class="btn btn-default" id="height_5" name="height" value="5" data-preview="preview_hl_height" onkeyup="validate()" onclick="validate()">72,5</button>
</div>
我一直试图通过以下方式找到所选按钮的值:
document.getElementsByName('aantal_planken')[0].value = document.getElementsByName('height')[0].value;
但这总是回显第一个按钮的值而不是所选按钮。 如何获取所选按钮的值?
答案 0 :(得分:2)
您需要在click函数中将单击的按钮引用作为this
传递,然后使用它来获取单击的按钮值,如下所示 -
<div class="btn-group">
<button type="button" class="btn btn-default" id="height_1" name="height" value="1" data-preview="preview_hl_height" onkeyup="validate(this)" onclick="validate(this)">14,5</button>
<button type="button" class="btn btn-default" id="height_2" name="height" value="2" data-preview="preview_hl_height" onkeyup="validate(this)" onclick="validate(this)">29,0</button>
<button type="button" class="btn btn-default" id="height_3" name="height" value="3" data-preview="preview_hl_height" onkeyup="validate(this)" onclick="validate(this)">43,5</button>
<button type="button" class="btn btn-default" id="height_4" name="height" value="4" data-preview="preview_hl_height" onkeyup="validate(this)" onclick="validate(this)">58,0</button>
<button type="button" class="btn btn-default" id="height_5" name="height" value="5" data-preview="preview_hl_height" onkeyup="validate(this)" onclick="validate(this)">72,5</button>
</div>
<script type="text/javascript">
function validate(ele) {
console.log(ele.value);
console.log(ele.innerText);
}
</script>