【问题标题】:Multiplying radio button values by a textbox value in javacsript? [closed]将单选按钮值乘以javascript中的文本框值? [关闭]
【发布时间】:2018-04-08 23:19:16
【问题描述】:

所以我对编程很陌生,但是我有一个 HTML 表单,其中包括用户可以从中选择的 5 个单选按钮和一个用户需要在其中写入数字的文本框。当用户按下计算按钮时,我想将所选单选按钮的值乘以写入文本框中的值。我一直在尝试使用 HTML 表单中的脚本来执行此操作,但我无法让它工作。有人可以帮忙吗???

【问题讨论】:

  • 请不要破坏您的帖子。
  • 对不起,它没有被取消,所以我只是想摆脱它
  • @JoeCole2233 你可以删除它然后
  • 它说我不能,因为其他人已经回答了。 @gsquaredxc
  • 我认为模组会知道这个网站是如何运作的,哈哈@gsquaredxc

标签: javascript html css


【解决方案1】:

首先,您需要获得对文本输入的引用,然后您需要获得选中的单选按钮,这可以通过查询选择器来完成。然后,您只需将两者相乘即可。

这是最基本的方法:

let input = document.querySelector('input[type=number]')
let checked = document.querySelector('[name=radio]:checked')

let result = parseFloat(input.value) * parseFloat(checked.value)

这是一个工作示例:

// Get reference to the input field
let input = document.querySelector('input[type=number]')
let output = document.querySelector('output')

// Create radio button event listeners
Array.from(document.querySelectorAll('input[type=radio]')).forEach(input => {
  // When the radio changes recalculate
  input.addEventListener('change', e => {
    e.preventDefault()
    calculate()
  })
})

// And the textbox event listner
// When the value changes recalculate
input.addEventListener('input', e => {
  e.preventDefault()
  calculate()
})

// Make calculation
function calculate() {
  // Get the checked radio
  let checked = document.querySelector('[type=radio]:checked')
  // Get its value. If no radio is checked default to 0
  let value = checked ? checked.value : 0
  // Multiply the radio time the text box
  let result = parseFloat(value) * parseFloat(input.value)
  // Set the output value use 0 if the result is not a number
  output.value = !isNaN(result) ? result : 0
}
<form>
  <label><input type="radio" value="1" name="radio"> 1</label>
  <label><input type="radio" value="2" name="radio"> 2</label>
  <label><input type="radio" value="3" name="radio"> 3</label> &times;
  <input type="number" id="txt" placeholder="Enter a number"> =
  <output>0</output>
</form>

【讨论】:

    【解决方案2】:

    我希望这将帮助您创建类似于您所要求的逻辑。谢谢。

    function testcalc(){
    var val1= parseInt($("input[name='multiplier']:checked")[0].value);
    var val2= parseInt($("#testinput")[0].value);
    $('#testanswer').text(val1*val2);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" id="testinput" value="0">
    <input type="radio" name="multiplier" value="2">2
    <input type="radio" name="multiplier" value="3">3
    <input type="radio" name="multiplier" value="4">4
    <input type="radio" name="multiplier" value="5">5
    <input type="radio" name="multiplier" value="6">6
    <button onClick="testcalc()">Calculate</button>
    <p><span id="testanswer"></span></p>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-23
      • 2013-08-26
      • 2014-09-24
      • 2014-04-28
      • 1970-01-01
      • 2015-04-30
      相关资源
      最近更新 更多