简体   繁体   English

在 JavaScript 中获取具有相同名称的多个选中复选框的值

[英]Getting Value of Multiple Selected Checkbox with Same Name in JavaScript

I can't seem to get the correct output. I am not sure if my for loop is the problem.我似乎无法获得正确的 output。我不确定我的 for 循环是否有问题。 Please excuse my variable names.请原谅我的变量名。 I know I know, I made them very obvious.我知道我知道,我让他们很明显。 :) By the way, should I use var here or let is fine? :) 顺便问一下,我应该在这里使用 var 还是 let 好?

I have read somewhere that when declaring a variable:我在某处读到声明变量时:

var => function-scoped var => 函数范围

ES6 (ES2015): let, const => block-scoped ES6 (ES2015): let, const => 块作用域

The check all button won't work as well.选中所有按钮也不会起作用。

Your input will be highly appreciated.非常感谢您的意见。

<html>
 <head>
  <title>Get Checkbox Value</title>
  <style type="text/css">
      body {
          padding-top: 10px;
          font-family: Verdana, Geneva, Tahoma, sans-serif;
          background-color: #ede5e5;
          height: 100vh;
      }
      div { 
          width: 50%;
          margin: auto;
          border: 1px solid lightgray;
          border-radius: 5px;
          -webkit-box-shadow: 0 1px 2px 0 rgb(34 36 38 / 15%);
          box-shadow: 0 1px 2px 0 rgb(34 36 38 / 15%);
          padding: 10px;
          padding-left: 20px;
          padding-bottom: 30px;
          background-color: white;
      }
      button {
          padding:5px;
          font-size: 16px;
          font-weight: bold;
      }
      label {
          font-size: 18px;
          font-weight: bold;
      }
      input [type=checkbox] {
          width: 20px;
          height: 20px;
      }

  </style>

 </head>
<body>
    <div style="">
      <h2>Select a Programming Language You Love</h2>
      <form id="frm-lang">
          
          <input type="checkbox" name="languages" value="JavaScript">
          <label>JavaScript</label><br/>

          <input type="checkbox" name="languages" value="PHP">
          <label>PHP</label><br/>

          <input type="checkbox" name="languages" value="Pyton">
          <label>Pyton</label><br/>

          <input type="checkbox" name="languages" value="C#">
          <label>C#</label><br/>

          <input type="checkbox" name="languages" value="C++">
          <label>C++</label><br/><br/>

          <button id="btnSubmit">Submit</button>
          <button id="btnCheckAll">Check All</button>


      </form>


    </div>
     <script>
         let formvar = document.getElementById('frm-lang');  
         let valuesvar = [];

         formvar.addEventListener('submit', function(e) {   
          e.preventDefault ();
          let checkboxesvar = document.getElementsByName('languages');
          for (let i = 0; i < checkboxesvar.length; i++) {  
              if (checkboxesvar[i].checked == true) {  
              
                  valuesvar.push(checkboxesvar[i].value);  
              }   
          }

           alert('The values(s): ' + valuesvar.toString());
         });   

         // for the check all button

         document.getElementById('btnCheckAll').onclick = function(e) {
             e.preventDefault();
             let checkboxesvar = document.getElementsByName('languages');
             for (let i=0; i < checkboxesvar.length; i++) {
                 checkbboxesvar[i].checked = true;
             }
         }


            
     </script>

</body>
</html>

In your submit listener, you are not clearing your array, so it will keep the values from the previous submission, you need to clear it, so move it to inside the listener在您的submit侦听器中,您没有清除您的数组,因此它将保留上一次提交的值,您需要清除它,因此将其移至侦听器内部

in your checkAll you had a typo, checbboxesvar with 2 b在您的checkAll中,您有一个错字,带有 2 bchecbboxesvar

I improved your code a bit, renamed variable names and left one line solutions.我稍微改进了您的代码,重命名了变量名并留下了一行解决方案。

 const form = document.getElementById('frm-lang'); const checkboxes = document.getElementsByName('languages'); const checkAll = document.getElementById('btnCheckAll'); const clearAll = document.getElementById('btnClearAll'); form.addEventListener('submit', e => { e.preventDefault(); let values = []; // for loop solution //for (let i = 0; i < checkboxes.length; i++) { // if (checkboxes[i].checked) { // values.push(checkboxes[i].value); // } //} //one liner solution checkboxes.forEach(el => el.checked && values.push(el.value)) console.log('The values(s): ' + values); }); // for the check all button checkAll.addEventListener('click', () => { // for loop solution //for (let i = 0; i < checkboxes.length; i++) { // checkboxes[i].checked = true; //} //one liner solution checkboxes.forEach(el => el.checked = true) }) clearAll.addEventListener('click', () => { // for loop solution //for (let i = 0; i < checkboxes.length; i++) { // checkboxes[i].checked = false; //} //one liner solution checkboxes.forEach(el => el.checked = false) })
 body { padding-top: 10px; font-family: Verdana, Geneva, Tahoma, sans-serif; background-color: #ede5e5; height: 100vh; } .container { width: 50%; margin: auto; border: 1px solid lightgray; border-radius: 5px; box-shadow: 0 1px 2px 0 rgb(34 36 38 / 15%); padding: 10px 10px 30px 20px; background-color: white; } button { padding: 5px; font-size: 16px; font-weight: bold; } label { font-size: 18px; font-weight: bold; } input[type=checkbox] { width: 20px; height: 20px; }
 <div class="container"> <h2>Select a Programming Language You Love</h2> <form id="frm-lang"> <input type="checkbox" name="languages" value="JavaScript"> <label>JavaScript</label><br/> <input type="checkbox" name="languages" value="PHP"> <label>PHP</label><br/> <input type="checkbox" name="languages" value="Pyton"> <label>Pyton</label><br/> <input type="checkbox" name="languages" value="C#"> <label>C#</label><br/> <input type="checkbox" name="languages" value="C++"> <label>C++</label><br/><br/> <button id="btnSubmit">Submit</button> <button type="button" id="btnCheckAll">Check All</button> <button type="button" id="btnClearAll">Clear All</button> </form> </div>

你拼错了 checkboxesvar 你的变量是 checkboxesvar

Any <button> that's nested within a <form> is type="submit" by default, so add type="button" to the "Check All" button and you don't need anything on a <button> if it triggers a submit event.默认情况下,嵌套在<form>中的任何<button>都是type="submit" ,因此将type="button"添加到“Check All”按钮,如果<button>触发了提交事件。

The example uses the HTMLFormElement and HTMLFormControlsCollection interfaces to reference all Form Controls .该示例使用HTMLFormElementHTMLFormControlsCollection接口来引用所有表单控件 Also, the "Check All" button toggles all checkboxes checked/unchecked.此外,“全选”按钮可切换选中/未选中的所有复选框。

Details are commented in example细节在例子中注释

 .as-console-row::after { width: 0; font-size: 0; } .as-console-row-code { width: 100%; word-break: break-word; } .as-console-wrapper { max-height: 60% !important; max-width: 25%; }
 <html> <head> <title>Get Checkbox Value</title> <style> html { font: 900 2.5ch/1.2 Veranda; } body { padding-top: 10px; height: 100vh; } fieldset { width: 50%; margin: auto; border: 1px solid lightgray; border-radius: 5px; box-shadow: 0 1px 2px 0 rgb(34 36 38 / 15%); padding: 10px; padding-left: 20px; padding-bottom: 30px; background-color: white; } menu { display: flex; justify-content: flex-end; align-items: center; margin: 0; list-style: none; } button { padding: 3px 5px; font: inherit; cursor: pointer; } input [type=checkbox] { width: 20px; height: 20px; } </style> </head> <body> <form id="lang"> <fieldset> <legend> <h2>Favorite Language</h2> </legend> <input type="checkbox" name="languages" value="JavaScript"> <label>JavaScript</label><br/> <input type="checkbox" name="languages" value="PHP"> <label>PHP</label><br/> <input type="checkbox" name="languages" value="Python"> <label>Python</label><br/> <input type="checkbox" name="languages" value="C#"> <label>C#</label><br/> <input type="checkbox" name="languages" value="C++"> <label>C++</label><br/><br/> <menu> <button>Submit</button> <button id="all" type='button'>Check All</button> </menu> </fieldset> </form> <script> // Reference the form const form = document.forms.lang; // Reference all inputs, buttons, and fieldsets const IO = form.elements; // Collect all [name='languages'] into an array const chx = [...IO.languages]; /* Bind an event handler to the submit event When <form> is submitted instead of the default behavior the values of all checkboxes will be collected into an array then logged on console */ let values; form.onsubmit = collectValues; function collectValues(e) { e.preventDefault(); values = chx.map(c => c.value); console.log(values); } /* Bind button#all to the click event Invoke toggleCB(e) when clicked */ IO.all.onclick = toggleCB; function toggleCB(e) { // Toggle the ".check" class on button this.classList.toggle('check'); /* If the button has ".check" class... ...check all checkboxes... ...otherwise uncheck all checkboxes */ if (this.classList.contains('check')) { chx.forEach(c => c.checked = true); } else { chx.forEach(c => c.checked = false); } } </script> </body> </html>

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

相关问题 javascript从选定的复选框中检索输入值,并在同一网页中显示多个html文件 - javascript Retrieve input value from a selected checkbox and display multiple html file in same webpage 在javascript和PHP中的字符串中获取多个选中的复选框值 - Getting multiple selected checkbox values in a string in javascript and PHP 具有类名的多个复选框更改功能,但在javascript中具有相同的类名 - multiple checkbox change function with class name, but same class name in javascript 如何使用 javascript 获取多个单选按钮具有相同名称的选定单选按钮的值 - How to get the value of selected radio button where multiple radio buttons have same name using javascript HTML复选框,多个具有相同的“名称”。 如果选中,则值为1,如果未选中,则值为0 - Html Checkbox, multiple with same 'name'. Value 1 if checked, Value 0 if not checked 从一组具有相同类名的复选框中获取当前复选框的值 - Getting the value of current checkbox from a group of checkboxes with same class name 多个复选框名称-单击后获取复选框的值 - Multiple Checkbox Name - Getting the value of checkebox after it was clicked JavaScript中的多个复选框值 - Multiple checkbox value in javascript 选择多个具有相同名称的复选框 - Select multiple checkbox with same name jquery复选框有助于获取复选框名称和值 - jquery checkbox help getting checkbox name and value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM