【问题标题】:update field on radio select无线电选择上的更新字段
【发布时间】:2017-03-13 17:45:06
【问题描述】:

在表单中,我有一组带有固定捐赠金额的单选按钮和另一个字段,当用户可以输入选择的金额时。为简单起见,在处理表单时,我想要一个功能,其中选择的任何内容都填充在另一个字段中。我有下面的 HTML/JS:

$("input[id^='radio']").click(function() {
  $("input[name='otheramount']").val(jQuery(this).val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-select">
  <input type="radio" name="selamount" id="amount-1" value="10.00">
  <label for="amount-1">$10</label>
</div>
<div class="radio-select">
  <input type="radio" name="selamount" id="amount-2" value="15.00">
  <label for="amount-2">$15</label>
</div>
<div class="radio-select">
  <input type="radio" name="selamount" id="amount-3" value="20.00">
  <label for="amount-3">$20</label>
</div>
<div class="radio-select">
  <input type="radio" name="selamount" id="amount-3" value="20.00">
  <label for="amount-4">$25</label>
</div>

<div class="form-group other-amount col-lg-3 col-md-8 col-xs-12 padd-top-10"></div>
<input type="text" id="otheramount" name="otheramount" value="" placeholder="Or Other Amount">

我也试过

<input type="radio" name="selamount" id="amount-3" value="20.00" onclick="document.getElementById('otheramount').value = this.value">

但是当第一个改变时,它在随后的点击中不再改变。

【问题讨论】:

  • 没有 &lt;input&gt; 元素的 id 属性包含单词 radio

标签: javascript jquery radio-group


【解决方案1】:

您的所有 ID 都没有以“radio”开头,这是您的 [id^='radio'] 选择器试图匹配的。

它们以“金额”开头,因此您应该使用:

$("input[id^='amount']").click(...

此外,还有一个可以用于标签的技巧。

而不是做:

<input type="radio" name="selamount" id="amount-1" value="10.00">
<label for="amount-1">$10</label>

...您可以将输入放在标签内,完全避免使用for 属性:

<label>
  <input type="radio" name="selamount" id="amount-1" value="10.00">
  $10
</label>

工作片段

$("input[id^='amount']").click(function() { //CHANGE THIS
  $("input[name='otheramount']").val(jQuery(this).val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-select">
  <label>
    <input type="radio" name="selamount" id="amount-1" value="10.00">
    $10
  </label>
</div>
<div class="radio-select">
  <label>
    <input type="radio" name="selamount" id="amount-2" value="15.00">
    $15
  </label>
</div>
<div class="radio-select">
  <label>
    <input type="radio" name="selamount" id="amount-3" value="20.00">
    $20
  </label>
</div>
<div class="radio-select">
  <label>
    <input type="radio" name="selamount" id="amount-3" value="20.00">
    $25
  </label>
</div>

<div class="form-group other-amount col-lg-3 col-md-8 col-xs-12 padd-top-10">
  <input type="text" id="otheramount" name="otheramount" value="" placeholder="Or Other Amount">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-12
    • 2011-07-27
    • 1970-01-01
    • 2016-07-30
    • 2017-03-15
    • 2020-04-30
    • 2011-11-19
    • 2012-08-18
    相关资源
    最近更新 更多