0

我有 2 个单选按钮。一个单选按钮有 3 个子级单选按钮。前任:

    <input type="radio"  name="catagory" />
                  <label class="" for="">A</label>
  <input type="radio" class="btn-redio" name="catagory" />
                  <label class="" for="">B</label>

一旦我检查了单选按钮 B,我将获得 3sub 级别的单选按钮。我想验证如果用户单击 B 则需要检查是否选中了任何子单选按钮。

子级别的意思是:如果点击按钮B,那么JS只会显示另外3个单选按钮

谢谢

AZ

4

1 回答 1

1

如果我理解正确,这是您的情况:

<input type="radio" name="parent_radio1" value="..." />
<input type="radio" name="sub_radio1_1" value="..." />
<input type="radio" name="sub_radio1_2" value="..." />
<input type="radio" name="sub_radio1_3" value="..." />

<input type="radio" name="parent_radio2" value="..." />
<input type="radio" name="sub_radio2_1" value="..." />
<input type="radio" name="sub_radio2_2" value="..." />
<input type="radio" name="sub_radio2_3" value="..." />

如果是这种情况,您可以使用这样的东西(未经测试):

var form = $('#someForm');
form.submit(function(event){
  var parent_radios = $('input[type=radio][name^="parent_radio"]');
  parent_radios.each(function(){
    var parent = $(this);

    if (parent.prop('checked') !== true) return; // Parent not selected, no validation needed

    var child_selector = parent.attr('name').replace('parent_radio', '');
    var childs = $('input[name^="sub_radio' + child_selector + '_"]:checked'); // Select only the selected ones

    if (childs.length == 0) {
      event.preventDefault(); // No sub radio has been selected for this parent, cancel submit
      // Do some other stuff here like show error message
    }
  });

});
于 2013-04-24T11:50:22.970 回答