javascript - 将 document.getElementById 用于复选框的更有效方法?

标签 javascript jquery forms checkbox

这部分代码使用 jQuery 来隐藏/显示表单域。当它们被隐藏时,这些字段的值被设置为空。这对于具有唯一 ID 的输入字段来说很容易。我在使用复选框时遇到了麻烦。下面的代码适用于三个复选框。但是我必须对一组 26 个复选框使用相同的技术。我怎样才能更有效地做到这一点?

$(".transfer").click(function(){
    if ($('input[name=transfer_position]:checked').val() == "yes" ) {
        //Slide Down Effect
        $(".transfer_details").slideDown("slow");
        document.getElementById('transfer_interest').focus();
    } else {
         //Slide Up Effect
        $(".transfer_details").slideUp("slow");
        document.getElementById('transfer_interest').value = "";
        document.getElementById('select_positions_0').checked = false;
        document.getElementById('select_positions_1').checked = false;
        document.getElementById('select_positions_2').checked = false;
    }
 });

  <li>
      <label>
        <input type="radio" name="transfer_position" class="transfer" value="yes" id="transfer_position_0" />
        Yes</label>
      <label>
        <input type="radio" name="transfer_position" class="transfer" value="no" id="transfer_position_1" />
        No</label>
  </li>
  <li class="transfer_details">
    <label for="transfer_interest">Why are you interested in transferring to your selected SL positions and what would you bring to that position(s) and team(s)?</label>
    <textarea name="transfer_interest" id="transfer_interest" cols="80" rows="6"> </textarea>
  </li>
  <li class="transfer_details">
      <label>
        <input type="checkbox" name="select_positions[]" class="select_positons" value="Resident Advisor" id="select_positions_0" />
        Resident Advisor</label>
      <label>
        <input type="checkbox" name="select_positions[]" class="select_positons" value="Programming Assistant" id="select_positions_1" />
        Programming Assistant</label>
      <label>
        <input type="checkbox" name="select_positions[]" class="select_positons" value="Social Justice Advocate " id="select_positions_2" />
        Social Justice Advocate </label>
  </li>

最佳答案

使用类,因为许多元素可以共享一个类。所以你只需取消选中某个类的所有复选框:

$('.select_positions').attr('checked', false);

关于javascript - 将 document.getElementById 用于复选框的更有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20668981/

相关文章:

javascript - 从数组动态创建对象

javascript - 将保存代码放入文本框中,然后将变量更改为该保存代码

javascript - 提交表单时未调用 jQuery .submit()

jquery - HTMLDOM : How to change text "files selected" from upload button using jquery or javascript?

javascript - HTML5 视频 : get seek-from position

javascript - 比较当前日期和日期 inp

javascript - keyup 事件总是返回大写字母

javascript - jQuery 不取消选中复选框

javascript - jQuery Validate with fixed header 验证

php - 使用表单按钮提交 GET 值