简体   繁体   中英

Checkbox value only when checked

I'm trying to get the checkbox output to a variable x only when checked. Now it passes the value of checkbox even unchecked

 function myFunction(){
        
     var  x  =parseInt(document.getElementById('cough').value)+
     parseInt(document.getElementById('cold').value)+ 
     parseInt(document.getElementById('fever').value) + 
     parseInt(document.getElementById('breathlessness').value) +
     parseInt(document.getElementById('loss of senses').value) + 
     parseInt(document.getElementById('sore throat').value) +
     parseInt(document.getElementById('none').value) +
     parseInt(document.getElementById('diabeties').value)+
     parseInt(document.getElementById('heart disorder').value) +
     parseInt(document.getElementById('lung disorder').value)+
     parseInt(document.getElementById('kidney disorder').value) + 
     parseInt(document.getElementById('hypertension').value) + 
     parseInt(document.getElementById('no disorder').value);
        
          console.log(x)
    }

I need to get these values only when checked

Basically you need the checked -property of a checkbox. So, you could use something like

// ...
(document.getElementById('hypertension').checked ? 
 parseInt(document.getElementById('hypertension').value) : 0) + 
(document.getElementById('heart disorder') ? 
 parseInt(document.getElementById('heart disorder').value) : 0)
// ...

That will become bulky quite fast. Here's a bit of checkbox magic you may want to study

Lookups:

 document.addEventListener("change", checkTheBoxes); function checkTheBoxes(evt) { if (evt.target.type && evt.target.type === "checkbox") { console.clear(); // handle 'none' if (evt.target.checked && +evt.target.value < 1) { document.querySelectorAll("input[type='checkbox']").forEach(v => v.checked = +v.value > 0? false: v.checked); } else { document.querySelector("input[type='checkbox'][value='0']").checked = false; } // filter checked checkboxes const values = [...document.querySelectorAll("input[type='checkbox']")].filter(v => v.checked); if (values.length) { console.log( `total ${values.reduce( (a, v) => a + +v.value, 0)}` ); // ^ use + to convert to Number } else { console.log( "no values checked (yet)"); } } }
 <input type="checkbox" value="1"> cough <input type="checkbox" value="2"> cold <input type="checkbox" value="3"> fever <input type="checkbox" value="4"> breathlessnes <input type="checkbox" value="0"> none

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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