从单选按钮的Javascript实时计算

时间:2016-10-22 22:26:17

标签: javascript input calculator live

有一些单选按钮

<input type="radio" name="highlight" data-price="25.1" value="a1">a1
<input type="radio" name="highlight" data-price="55.4" value="a2">a2
<input type="radio" name="highlight" data-price="65.3" value="a3">a3
<input type="radio" name="highlight" data-price="95.9" value="a4">a4

我想用实时更改打印所选单选按钮的“数据价格”。我该怎么做?

2 个答案:

答案 0 :(得分:0)

我不知道你究竟在问什么..但如果你只是想打印数据价格,你可以这样做。

$(function(){
  $('input[type=radio]').on('click',function(){
    data= $(this).data('price');
    $('#result').text(data);
   
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="highlight" data-price="25.1" value="a1">a1
<input type="radio" name="highlight" data-price="55.4" value="a2">a2
<input type="radio" name="highlight" data-price="65.3" value="a3">a3
<input type="radio" name="highlight" data-price="95.9" value="a4">a4

<div id='result'>
</div>

答案 1 :(得分:0)

HTML

<input class='radio' type="radio" name="highlight" data-price="25.1" value="a1">a1
<input class='radio' type="radio" name="highlight" data-price="55.4" value="a2">a2
<input class='radio' type="radio" name="highlight" data-price="65.3" value="a3">a3
<input class='radio' type="radio" name="highlight" data-price="95.9" value="a4">a4
<input id="price" type="text">

Javascript(onclick)

var inputs = document.getElementsByClassName('radio');
var textbox = document.getElementById('price');
var i;
for (i = 0; i < inputs.length; i++) {
    inputs[i].onclick = function(){
        textbox.value = this.dataset.price;
    }
}

Javascript(eventListener)

for (i = 0; i < inputs.length; i++) {
    function myFn(){
        textbox.value = this.dataset.price;
    }
    inputs[i].addEventListener("change",myFn);
}

https://jsfiddle.net/2zfjfkhL/