Using document.getElementsByClass with Checkboxes - javascript

I have cut this code and I'm not that familiar using Class.
<form>
<input type="checkbox" name="Symptom1" class=sound value="case1"> Poor Sound Quality<br>
<input type="checkbox" name="Symptom2" class=sound value="case2"> Only One Speaker is Working<br>
<input type="checkbox" name="Symptom3" class=sound value="case3"> No Sound<br>
<input type="checkbox" name="Symptom4" class=sound value="case4"> Low Volume<br>
<input type="checkbox" name="Symptom5" class=sound value="case5"> Crackling Sound<br>
<input type="checkbox" name="Symptom6" class=battery value="case6"> Drain Easily<br>
<input type="checkbox" name="Symptom7" class=battery value="case7"> Flickering Screen<br>
<input type="checkbox" name="Symptom8" class=battery value="case8"> Battery Physically Wobbled<br>
<input type="checkbox" name="Symptom9" class=battery value="case9"> Turn Off from Now and Then<br>
<input type="checkbox" name="Symptom10" class=battery value="case10"> Does not Charge<br>
</form>
<button onclick="Submit()">Submit</button>
Here is my submit function that I am working on.
function Submit() {
if (document.getElementsByClassName('sound').checked) {
alert("You Picked Sound");}
} else {
alert("none");
}
}
What I wanted to do is if the user checked at least one of the checkboxes under the same class (i.e. sound) then pressed submit. It would alert the user that he/she picked that class. But apparently it would not and rather it always alert me with none.
Help?

You have to loop through the collection document.getElementsByClassName returns and check the checked attribute. Here's one way to do it (untested):
function Submit() {
var pickedOne = false;
var inputs = document.getElementsByClassName('sound');
for(var i = 0, l = inputs.length; i < l; ++i) {
if(inputs[i].checked) {
pickedOne = true;
alert('You picked ' + inputs[i].className);
break;
}
}
if(!pickedOne) {
alert('none');
}
}
If you can use jQuery, you can probably do something like this instead:
function Submit() {
var selectedClass = $('input[type=checkbox]:checked').attr('class');
if(selectedClass) {
alert('You picked ' + selectedClass);
}
else {
alert('none');
}
}

"document.getElementsByClassName" return a list of nodes.
For example document.getElementsByClassName('sound') will return an array 5 checkboxes. So you can use it like this:
var sounds = document.getElementsByClassName('sound');
// Now you can access one of them through it's index
function Submit() {
if (document.getElementsByClassName('sound')[0].checked) {
alert("You Picked Sound");}
} else {
alert("none");
}
}

document.getElementsByClassName() returns an array instead of an object. You need to loop through the array.
function Submit() {
var allCheckBox = document.getElementsByClassName('sound');
var allPick = false;
for(var i = 0; i < allCheckBox.length ; i++) {
if (allCheckBox[i].checked) {
allPick = true;
break;
}
}
if(allPick) {
alert("You Picked Sound");
} else {
alert("none");
}
}

Related

Making checkboxes checked using same id using Javascript

This is my code to make check boxes checked with same id
<input type="checkbox" name="MassApprove" value="setuju2" />
<input type="checkbox" name="MassApprove" value="setuju3" />
<input type="checkbox" name="MassApprove" value="setuju4" />
<input type="checkbox" name="MassApprove" value="setuju5" />
<input type="submit" value="Next Step" name="next" />
And This is my javascript code. I need to make this checkboxes as checked when am trigger this function. Help me!..
function doMassApprove(massApproveFlag) {
var confirmAlert = confirm("Do You Need Mass Approve !..");
var massApprove = document.getElementById("MassApprove").length();
if (confirmAlert == true) {
//alert(massApproveFlag);
for (var i = 0; i < massApprove; i++) {
document.getElementById("MassApprove").checked = true;
}
} else {
document.getElementById("headerMassApprove").checked = false;
}
}
IDs in HTML must be unique.
As you have already specified the name MassApprove, use Document.getElementsByName(),
Returns a nodelist collection with a given name in the (X)HTML document.
Which you can iterate using simple for loop
function doMassApprove(massApproveFlag) {
var confirmAlert = confirm("Do You Need Mass Approve !..");
if (confirmAlert) {
//Get elements with Name
var massApproves = document.getElementsByName("MassApprove");
//Iterate and set checked property
for (var i = 0; i < massApprove.length; i++) {
massApproves[i].checked = true;
}
} else {
document.getElementById("headerMassApprove").checked = false;
}
}
you do not have the same ID and should not since ID must be unique. You have the same NAME and that is fine. -
Do not user getElementById for names, instead use document.getElementsByName which will return a collection you can loop over
Like this
function doMassApprove(massApproveFlag) {
var massApprove = confirm("Do You Need Mass Approve !..");
if (massApprove) {
var checks = document.getElementsByName("MassApprove");
for (var i=0; i < checks.length; i++) {
checks[i].checked = massApprove; // or perhaps massApproveFlag?
}
}
else {
document.getElementById("headerMassApprove").checked = false;
}
}
Just for the heck of it, you can use some modern browser goodness:
Array.prototype.forEach.call(document.querySelectorAll('[name=MassApprove]'), function(cb){cb.checked = true});
and with arrow functions:
Array.prototype.forEach.call(document.querySelectorAll('[name=MassApprove]'), cb => cb.checked=true);

Validating a checkbox after already validating other sections of a form [duplicate]

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.
JS (wrong)
function valthis(){
if (document.FC.c1.checked) {
alert ("thank you for checking a checkbox")
} else {
alert ("please check a checkbox")
}
}
HTML
<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"/> C1
<br>
<input type = "checkbox" name = "c1" value = "c2"/> C2
<br>
<input type = "checkbox" name = "c1" value = "c3"/> C3
<br>
<input type = "checkbox" name = "c1" value = "c4"/> C4
<br>
</form>
<br>
<br>
<input type = "button" value = "Edit and Report" onClick = "valthisform();">
So what I ended up doing in JS was this:
function valthisform(){
var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked
if (chkd == true){
} else {
alert ("please check a checkbox")
}
}
I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.
You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?
Here's a non-jQuery solution to check if any checkboxes on the page are checked.
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.
This should work:
function valthisform()
{
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
if(okay)alert("Thank you for checking a checkbox");
else alert("Please check a checkbox");
}
If you have a question about the code, just comment.
I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/
I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them.
Let's begin with giving the checkboxes a class so we can round them up very nicely.
I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.
HTML
<input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
<input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
JavaScript
function atLeastOneCheckboxIsChecked(){
const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}
When called, the function will return false if no checkbox has been checked and true if one or both is.
It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true.
the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.
Check this.
You can't access form inputs via their name. Use document.getElements methods instead.
Vanilla JS:
var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable
function activitiesReset() {
var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead.
if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
error[2].style.display = 'block'; // red error label is now visible.
}
}
for (var i=0; i<checkboxes.length; i++) { // whenever a checkbox is checked or unchecked, activitiesReset runs.
checkboxes[i].addEventListener('change', activitiesReset);
}
Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange event (written as .addEventListener('change', function(){});
You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" > < / script >
< script type = "text/javascript" >
function checkSelectedAtleastOne(clsName) {
if (selectedValue == "select")
return false;
var i = 0;
$("." + clsName).each(function () {
if ($(this).is(':checked')) {
i = 1;
}
});
if (i == 0) {
alert("Please select atleast one users");
return false;
} else if (i == 1) {
return true;
}
return true;
}
$(document).ready(function () {
$('#chkSearchAll').click(function () {
var checked = $(this).is(':checked');
$('.clsChkSearch').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
} else {
checkBox.prop('checked', false);
}
});
});
//for select and deselect 'select all' check box when clicking individual check boxes
$(".clsChkSearch").click(function () {
var i = 0;
$(".clsChkSearch").each(function () {
if ($(this).is(':checked')) {}
else {
i = 1; //unchecked
}
});
if (i == 0) {
$("#chkSearchAll").attr("checked", true)
} else if (i == 1) {
$("#chkSearchAll").attr("checked", false)
}
});
});
< / script >
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),
msg = document.getElementById('msg'),
onChange = function(ev){
ev.preventDefault();
let _this = this,
arrVal = Array.prototype.slice.call(
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))
.map(function(cur){return cur.value});
if(arrVal.length){
msg.innerHTML = JSON.stringify(arrVal);
} else {
_this.checked=true;
msg.innerHTML = "At least one value must be checked!";
}
};
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>
<div id="msg"></div>
$('input:checkbox[type=checkbox]').on('change',function(){
if($('input:checkbox[type=checkbox]').is(":checked") == true){
$('.removedisable').removeClass('disabled');
}else{
$('.removedisable').addClass('disabled');
});
if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
|| ($("#checkboxid3").is(":checked"))) {
//Your Code here
}
You can use this code to verify that checkbox is checked at least one.
Thanks!!

Javascript - Not Reversing the show/hide

I have created a fiddle
Would like to have the user hit 'yes' and it show the # field and then hit 'no' to hide it. Do I need another function on the 'no' to do this?
var empNumber, radios;
function showReqEmp() {
if (!radiosChecked()) {
empNumber.style.display = 'none';
} else {
empNumber.style.display = 'block';
}
}
function showReqEmp(id) {
var a = document.getElementById(id);
if (!radiosChecked())
a.style.display = 'none';
else
a.style.display = 'block';
}
function radiosChecked() {
var radios = document.getElementsByName('returning_employee');
for (var i = 0; i < radios.length; i++)
if (radios[i].checked) return true;
return false;
}
showReqEmp('requiredNum');
showReqEmp('requiredNumText');
<font color="Red">*</font>Returning Employee:</td>
<input type="radio" name="returning_employee" value="Yes" onclick="showReqEmp('requiredNum'); showReqEmp('requiredNumText')">Yes
<input type="radio" name="returning_employee" value="No" onclick="showReqEmp('requiredNumText'); showReqEmp('requiredNum')" />No
<lable id="requiredNumText" style="display:none"><font color="Red">*</font>Employee Number:</lable>
<lable id="requiredNum" style="display:none">
<input type="text" id="employee_number" name="employee_number" placeholder="123456789">
Ok so now I ran into this issue with the validation.
Fiddle2
The show/hide works but i cant get the validation to check if they entered data after hitting 'yes'
var numberExp = /^[0-9\-]+$/;
function validate()
{
if(document.newempRequest.returning_employee.checked && !(document.newempRequest.employee_number.value.match(numberExp)))
{
alert("Please provide the employee number");
document.newempRequest.employee_number.focus();
return false;
}
return true;
}
I have tried to alter the input tags to differ the yes/no but that breaks the show/hide
The HTML code is same as above.
Simply modify the radiosChecked function to return true only if the Yes checkbox is checked.
function radiosChecked() {
var radios = document.getElementsByName('returning_employee')[0];
return radios.checked;
}
The original Code:
var radios = document.getElementsByName('returning_employee');
for (var i = 0; i < radios.length; i++)
if (radios[i].checked) return true;
return false;
Would return true even if any of the check box in the group is checked. Hence the toggling would not happen.
You can do it CSS-only, without JS:
#requiredNum {
display: none;
}
#returning_employee_yes:checked ~ #requiredNum {
display: block;
}
*Returning Employee:
<input type="radio" name="returning_employee"
id="returning_employee_yes" value="Yes" />
<label for="returning_employee_yes">Yes</label>
<input type="radio" name="returning_employee"
id="returning_employee_no" value="No" />
<label for="returning_employee_no">No</label>
<label id="requiredNum">
*Employee Number:
<input type="text" id="employee_number"
name="employee_number" placeholder="123456789" />
</label>

Validating a single radio button is not working in available javascript validation script

I have randomly generated radio button series like
<input type="radio" name="creatorusers" value="1">
<input type="radio" name="creatorusers" value="1">
<input type="radio" name="creatorusers" value="1">
<input type="radio" name="creatorusers" value="1">
.....so on
But I get only ONE radio button and execute the javascript validation given for it to chk whether the radio button is selected or not, then it doesnt work
Ples help me out in resolving this.
mycreator = -1;
for (i=frm.creatorusers.length-1; i > -1; i--) {
if (frm.creatorusers[i].checked) {
mycreator = i; i = -1;
}
}
if (mycreator == -1) {
alert("You must select a Creator User!");
return false;
}
Always (!) use the var keyword. Otherwise your variables will be in the global scope (yes, even those in function bodies), which can make for some bugs that are hard to track down.
As #Felix pointed out, creatorusers will only be an array if there is more than one element with that name in the form. You can create a single-element array when necessary to work around that.
Here is an abstracted function that can validate an arbitrary checkbox list.
function ensureChecked(checkboxes, error) {
if (checkboxes) {
var cbx = (checkboxes.length > 0) ? checkboxes : [checkboxes];
for (var i=0; i<cbx.length; i++) {
if (cbx[i].checked) {
return true;
}
}
alert(error);
}
return false;
}
call as
ensureChecked(frm.creatorusers, "You must select a Creator User!");
Ah now I got. If you only have one radio button, then frm.creatorusers is not an array. Just skip it:
var mycreator = -1;
var checked = false;
if(typeof frm.creatorusers.length === 'number') {
for (var i=frm.creatorusers.length; i--; ) {
if (frm.creatorusers[i].checked) {
mycreator = i;
checked = true;
break;
}
}
}
else if(frm.creatorusers.checked){
mycreator = //? what here?
checked = true;
}
if(!checked) {
alert("You must select a Creator User!");
return false;
}
If mycreator was just for checking whether a button was selected or not, you can completely remove it from the code above.
Some further notes to your code:
Always declare variables with var, otherwise they will be global.
Use break to end a loop.
Maybe it is just because of copy and paste, but having a lot of radio buttons with the same value does not make much sense.
You can do something like this:
function validate(frm){
var isChecked = false;
for (var i=0; i<frm.elements.length; i++)
{
if (frm.elements[i].type === 'radio'){
if (frm.elements[i].checked === true){
isChecked = true;
break;
}
}
}
if (isChecked === true){
return true;
}
else{
alert('You should select an option first !');
}
}
Now you should call above function on onsubmit event of the form:
<form onsubmit="return validate(this);">
Now the validate function will make sure that at least one radio button is checked otherwise it won't submit.
this should do it
function isRadioSelected(btn) {
if(typeof btn.length === 'number') {
for(var i=0;i<btn.length;i++)
if(btn[i].checked) return true
}else{
if(btn.checked) return true
}
return false
}
You could try something like this instead:
<html>
<head>
<script type="text/javascript">
function confirmsubmit() {
var btn = document.formname.buttonname
if (btn.checked == false)
{
window.alert("You did not click the button.");
btn.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<form method="post" action="mailto:youremail#yourdomain.com"
name="formname" onsubmit="return confirmsubmit();">
click here: <input type="radio" name="buttonname"><br />
<p><input type="submit" value="Submit" name="submit"></p>
</form>
</body>
</html>

Using JavaScript to manipulate HTML input (checkbox) elements via type instead of name

I am implementing an HTML form with some checkbox input elements, and I want to have a Select All or DeSelect All button. However, I do not want to rely on the name of the input element (like this example) but rather the type because I have multiple checkbox groups with different names. Is there a way to check and uncheck all checkbox input elements within a form with JavaScript by relying on the type instead of the name?
Edit: We rely on YUI libraries, so I have access YUI if that provides a solution.
This should do it:
<script>
function checkUncheck(form, setTo) {
var c = document.getElementById(form).getElementsByTagName('input');
for (var i = 0; i < c.length; i++) {
if (c[i].type == 'checkbox') {
c[i].checked = setTo;
}
}
}
</script>
<form id='myForm'>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='button' onclick="checkUncheck('myForm', true);" value='Check'>
<input type='button' onclick="checkUncheck('myForm', false);" value='Uncheck'>
</form>
function findCheckBoxes(el, check) {
for(var i=0;el.childNodes[i];i++)
{
var child = el.childNodes[i];
if (child.type=="checkbox")
{
child.checked = check;
}
if (child.childNodes.length > 0)
this.findCheckBoxes(child, check);
}
}
iterate through the form.elements collection and check .type == "checkbox".
var button = getSelectAllButtonInFormSomeHow();
/*all formelements have a reference to the form. And the form has an elements-collection.*/
var elements = button.form.elements;
for(var i = 0; i < elements.length;i++) {
var input = elements[i];
if (input.tagName == "input" && input.type == "checkbox") input.checked = true;
}
Every input element has an attribute, type, which for checkboxes is "checkbox" so you could try something like this:
for (var i = 0; i < document.myForm.elements.length; i++) {
if (document.myForm.elements[i].type == "checkbox") {
document.myForm.elements[i].checked = true;
}
}
If jQuery is an option you can do this rather easily.
See the documentation on jQuery selectors. (The last example in the section shows how to do it with radio buttons but just replace that with check boxes.)
Is assigning a class to all required checkbox elements an option? If yes, then this is how I would do it (assuming "class_name" is the name of the css class present in all checkbox elements in question):
function selectCheckBoxes(bChecked) {
var aCheckBoxes = YAHOO.util.Dom.getElementsByClassName('class_name', 'input');
for (var i = 0; i < aCheckBoxes.length; i++) {
aCheckBoxes[i].checked = bChecked;
}
}
If you want to stay away from classes, but can get parent element by ID (or any other method, I will use ID in the example, though), than you can do this:
function selectCheckBoxes(bChecked) {
var oParent = document.getElementById('parentsID');
var aElements = oParent.getElementsByTagName('input');
for (var i = 0; i < aElements.length; i++) {
if (aElements[i].type == 'checkbox') {
aElements[i].checked = bChecked;
}
}
}
I would stick to the "class" method, however.
<html>
<head>
<script>
function selectCheckBox()
{
if(document.getElementById('id11').checked==true)
{
document.frm.id2.checked=true
document.frm.id3.checked=true
document.frm.id4.checked=true
}
if(document.getElementById('id11').checked==false)
{
document.frm.id2.checked=false
document.frm.id3.checked=false
document.frm.id4.checked=false
}
}
function selectCheckBox1()
{
if(document.getElementById('id12').checked==false)
{
document.frm.id1.checked=false
}
}
function selectCheckBox2()
{
if(document.getElementById('id13').checked==false)
{
document.frm.id1.checked=false
}
}
function selectCheckBox3()
{
if(document.getElementById('id14').checked==false)
{
document.frm.id1.checked=false
}
}
</script>
</head>
<body>
<form name="frm">
All :<input type="checkbox" id="id11" name="id1" value="1" onClick="selectCheckBox()"><br>
A. :<input type="checkbox" id="id12" name="id2" value="2" onClick="selectCheckBox1()"><br>
B. :<input type="checkbox" id="id13" name="id3" value="3" onClick="selectCheckBox2()"><br>
C. :<input type="checkbox" id="id14" name="id4" value="4" onClick="selectCheckBox3()"><br>
</form>
</body>
</html>

Categories

Resources