简体   繁体   English

根据使用Javascript的组中的值选中或取消选中复选框

[英]Checking or unchecking a checkbox based on value in a group with Javascript

I am really new to Javascript and know absolutely nothing about JQuery, so I apologize now for my newbie status. 我对Javascript真的很陌生,对JQuery完全一无所知,所以对于我的新手身份,我深表歉意。

I have an array of checkboxes (up to 18) that have the same name and class (can't change that fact): 我有一个复选框数组(最多18个),它们具有相同的名称和类(无法更改该事实):

<input type="checkbox" name="elective_id[]" value="112" class="elective_id">
<input type="checkbox" name="elective_id[]" value="128" class="elective_id">
<input type="checkbox" name="elective_id[]" value="135" class="elective_id">
<input type="checkbox" name="elective_id[]" value="322" class="elective_id" onClick="checkSister(322);">
<input type="checkbox" name="elective_id[]" value="323" class="elective_id" onClick="checkSister(323);">

Within that array will be 3 pairs of checkboxes that need their counterpart checked/unchecked when their pair is checked/unchecked. 在该阵列中将有3对复选框,当它们的复选框被选中/取消选中时,它们的对应复选框需要被选中/取消选中。 The three pairs are 320,321 & 322,323 & 345,346. 这三对分别为320321和322323和345346。

If checkbox with value 322 was selected, how can I automatically select the pair? 如果选中了值为322的复选框,如何自动选择该对?

function checkSister(brother) {
 if (brother=="322") {
  document.getElementById("322").checked = true;        
  document.getElementById("323").checked = true;
 } else if (brother=="322") {
  document.getElementById("322").checked = true;        
  document.getElementById("323").checked = true;
 }
}

I know that is not right, but haven't figured out how to get the right variable selected, let alone deselected. 我知道这是不对的,但是还没有弄清楚如何选择正确的变量,更不用说取消选择了。

Any help you can provide would greatly be appreciated, Jim 吉姆,您能提供的任何帮助将不胜感激。

You can do it easily without jquery using querySelectorAll 您可以轻松地做到这一点,而无需使用querySelectorAll进行jquery

document.querySelectorAll("input[type='checkbox'][value='112']")[0].checked=true;

or you can query by name and value like this: 或者您可以按如下名称和值进行查询:

document.querySelectorAll("input[name='elective_id[]'][value='112']")[0].checked=false;

To convert that vanilla JavaScript to jQuery, 要将原始JavaScript转换为jQuery,

function checkSister(brother) {
    if (brother=="322") {
      $("#322").prop("checked") = true;        
      $("#323").prop("checked") = true;  
 } else if (brother=="322") {
      $("#322").prop("checked") = true;     
      $("#323").prop("checked") = true;  
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM