86773

Making sure at least one checkbox is checked

Question:

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.

<blockquote>

JS (wrong)

</blockquote> function valthis(){ if (document.FC.c1.checked) { alert ("thank you for checking a checkbox") } else { alert ("please check a checkbox") } } <blockquote>

HTML

</blockquote>

Please select at least one Checkbox

<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();">
<blockquote>

So what I ended up doing in JS was this:

</blockquote> 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.

Answer1:

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.

Answer2:

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.

<hr />

<sup>I use l=checkboxs.length to improve the performance. See <a href="http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/" rel="nofollow">http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/</a></sup>

Answer3:

<a href="http://jsfiddle.net/qyE97/" rel="nofollow">Check this.</a>

You can't access form inputs via their name. Use document.getElements methods instead.

Answer4:

<strong>Vanilla JS:</strong>

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); }

<br /><strong>Explanation:</strong><br /> 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(){});

Answer5:

Using jQuery, bellow you can just prevent user from deselecting last checked checkbox.

<pre class="snippet-code-js lang-js prettyprint-override">$('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 $('#cont').html(getArrVal.toString()); } else { $(this).prop("checked",true); $('#cont').html("At least one value must be checked!"); return false; }; }); <pre class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <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="cont"></div>

Answer6:

You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.

Reference <a href="http://34codefactory.blogspot.in/2017/12/at-least-one-checkbox-is-checked-from.html" rel="nofollow">Link</a>

<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>

Answer7:

< 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 >

Recommend

  • hashmap in android xml parsing
  • Networkx node sizes
  • networkstream “cannot access a disposed object” when using newly created networkstream
  • Number of nodes returned in MutationRecord.addedNodes nodelist (mutationObserver)
  • Shouldn't else be indented in the below code
  • Convert SQLite database to XML
  • WPF Visiblity Binding to Boolean Expression with multiple Variables
  • Conversion from string “a” to type 'Boolean' is not valid
  • Caching attributes in superclass
  • WPF - CanExecute dosn't fire when raising Commands from a UserControl
  • Is it possible to access block's scope in method?
  • SignalR .NET Client Invoke throws an exception
  • Xamarin Forms - UWP Fonts
  • Arrow is showed instead of the material design version hamburger icon. Why doesn't syncState in
  • Why is the timeout on a windows udp receive socket always 500ms longer than set by SO_RCVTIMEO?
  • Rearranging Cells in UITableView Bug & Saving Changes
  • Matplotlib draw Spline from multiple points
  • XCode can't find symbols for a specific iOS library/framework project
  • R: gsub and capture
  • Calling of Constructors in a Java
  • jqPlot EnhancedLegendRenderer plugin does not toggle series for Pie charts
  • Compare two NSDates in iPhone
  • Arrays break string types in Julia
  • Transpose CSV data with awk (pivot transformation)
  • Comma separated Values
  • Use group_by to filter specific cases while keeping NAs
  • WPF Applying a trigger on binding failure
  • log4net write single file for each call to log.info
  • Benchmarking RAM performance - UWP and C#
  • Acquiring multiple attributes from .xml file in c#
  • Angular 2 constructor injection vs direct access
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • Change div Background jquery
  • How does Linux kernel interrupt the application?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • How can I remove ASP.NET Designer.cs files?
  • Busy indicator not showing up in wpf window [duplicate]
  • Why do underscore prefixed variables exist?
  • java string with new operator and a literal
  • How to load view controller without button in storyboard?