从多个表单列表中获取已检查的单选按钮值

时间:2015-12-10 17:53:05

标签: jquery forms

我有以下代码可以正常工作从获取的单选按钮获取值。然后我尝试添加多个单选按钮部分,但每次运行代码时都会在每个文本输入中添加文本。

我相信我需要在这个代码中的某个地方使用。但似乎无法弄清楚在哪里。

如果有人愿意看一下,我的代码就在下面的jsfiddle中。

无线电领域

<div class="dropdown">

   <input type="text" class="it" value="">
   <input type="radio" name="hey" value="one">
   <input type="radio" name="hey" value="two">
   <input type="radio" name="hey" value="three">

</div>

<div class="dropdown">

   <input type="text" class="it" value="">
   <input type="radio" name="hey" value="one">
   <input type="radio" name="hey" value="two">
   <input type="radio" name="hey" value="three">

</div>

Jquery

$(document).ready(function(){
   $("div.dropdown").each(function () {
      $("input[type=radio]").click(function(){
         $(".it").val(this.value);
      }); 
   });
});

3 个答案:

答案 0 :(得分:0)

我建议:

// binding the anonymous function of the on() method
// as the change event-handler:
$('input[type=radio]').on('change', function () {

    // caching the changed radio-input:
    var changed = this;

    // starting to traverse from that changed radio input:
    $(changed)
        // traversing to the closest ancestor element with
        // the class of 'dropdown':
        .closest('.dropdown')
        // looking within that element for an <input>
        // element with a 'type' attribute equal to 'text':
        .find('input[type=text]')
        // setting the value of that <input> to be equal
        // to the value of the cached radio input:
        .val(changed.value);
});

$('input[type=radio]').on('change', function() {
  var changed = this;

  $(changed)
    .closest('.dropdown')
    .find('input[type=text]')
    .val(changed.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown">

  <input type="text" class="it" value="">
  <input type="radio" name="group1" value="one">
  <input type="radio" name="group1" value="two">
  <input type="radio" name="group1" value="three">

</div>

<div class="dropdown">

  <input type="text" class="it" value="">
  <input type="radio" name="group2" value="one">
  <input type="radio" name="group2" value="two">
  <input type="radio" name="group2" value="three">

</div>

请注意,我还更改了每个组的name属性,以便他们代理作为单独的组。

参考文献:

答案 1 :(得分:0)

我认为,

  • 当您从单选按钮中选择一个值时,您的点击功能会执行。
  • 您想要更新与单选按钮相同的div下的文本值

然后你可以试试这个:

$(document).ready(function(){
   $("input[type=radio]").click(function(){
     $(this).closest("div.dropdown").find(".it").val(this.value);
  }); 
});

答案 2 :(得分:0)

您的代码非常接近 - 您只需更改选择器,使其仅在收音机之前更改输入。有很多不同的方法可以做到这一点。这是一个。

另外,我删除了.each迭代,因为它完全无关紧要。点击处理程序以完全相同的方式被注册两次,因为您是通过两个DIV在迭代中注册它。

$(document).ready(function(){
      $("input[type=radio]").click(function(){
         $(this).prevAll(".it").val(this.value);
      }); 
});