【问题标题】:Auto select correspondance radion in jquery在jquery中自动选择通信电台
【发布时间】:2018-07-30 17:48:25
【问题描述】:

我在一个 div 中有动态收音机 就像这里收音机的名称是动态的,并且值也是:

<input type="radio" name="first[1]" value="1" />
<input type="radio" name="first[2]" value="2" />
<input type="radio" name="first[3]" value="3" />


And the second div I have which have these radios : 

<input type="radio" name="second[1]" value="1" />
<input type="radio" name="second[2]" value="2" />
<input type="radio" name="second[3]" value="3" />

我的问题是,如果我选中(是)div first 单选按钮 然后div第二个收音机选择自动。这就像两个 div 收音机 一起检查是和否这两个条件。

我尝试这个来获取第一个 div 的值,但在这里我没有得到值..

<script type="text/javascript">
$(document).ready(function(){
alert('ok');
$('input:radio').on('click',function() { 
var obj=$('input[name="first"]:checked').val();
alert(obj);
});
});
</script>


Can any one please help me related this?

提供一些额外的信息,例如:

【问题讨论】:

  • 有什么解决办法吗???

标签: javascript jquery radio-button


【解决方案1】:

// Add your javascript here
$(function() {
  $('input[name^="first"],input[name^="second"]').on('change', function() {

    let i = $(this).index();
    $('input[name^="first"]').each(function(j) {
      $(this).prop('checked', i === j);
    });
    $('input[name^="second"]').each(function(j) {
      $(this).prop('checked', i === j);
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="radio" name="first[1]" value="1" />A
  <input type="radio" name="first[2]" value="2" />B
  <input type="radio" name="first[3]" value="3" />C
</div>


<div>
  <input type="radio" name="second[1]" value="1" />AA
  <input type="radio" name="second[2]" value="2" />BB
  <input type="radio" name="second[3]" value="3" />CC
</div>

【讨论】:

  • 在您的代码中,当您添加警报时,它会显示,但在我的情况下,警报不起作用,为什么...
  • 你有这一行$('input[name="first"]:checked').val();,但是你的输入元素中没有一个名称等于first...你有一个名称等于“first[1]”,另一个名称等于“first” [2]" 和另一个名称等于 "first[3]",因此使用选择器 'input[name="first":checked' 这不会带来任何东西,使用他使用的选择器:'input[name^= "first" 查找名称带有 "first" 的任何输入
【解决方案2】:
<script type="text/javascript">
$(document).ready(function(){
    var first = $('input[name^=first]');
    var second = $('input[name^=second]');
    first.change(function(){
        var index = $(this).index();
        if(this.checked){
            second.eq(index).prop('checked', true);
        }
});
</script>

【讨论】:

  • 你的代码在我的情况下不起作用...查看我更新的问题
猜你喜欢
  • 2012-12-24
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
  • 2011-08-12
  • 2021-10-29
  • 2014-12-26
  • 1970-01-01
  • 2014-12-19
相关资源
最近更新 更多