display message after checkbox limit - javascript

I found this snippet from another question but I am wondering how we can tweak it to display a message after the limit is reached. Is the best way to add a slideToggle to the .checkboxmsg in the function?
limit = 0; //set limit
checkboxes = document.querySelectorAll('.checkboxdiv input[type="checkbox"]'); //select all checkboxes
function checker(elem) {
if (elem.checked) { //if checked, increment counter
limit++;
} else {
limit--; //else, decrement counter
}
for (i = 0; i < checkboxes.length; i++) { // loop through all
if (limit == 2) {
if (!checkboxes[i].checked) {
checkboxes[i].disabled = true; // and disable unchecked checkboxes
}
} else { //if limit is less than two
if (!checkboxes[i].checked) {
checkboxes[i].disabled = false; // enable unchecked checkboxes
}
}
}
}
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].onclick = function() { //call function on click and send current element as param
checker(this);
}
}
<div class="checkboxdiv">
<input type="hidden" name="check" value="">
<input type="checkbox" name="check" value="One"><label>One</label> <br/>
<input type="checkbox" name="check" value="Two"><label>Two</label> <br/>
<input type="checkbox" name="check" value="Three"><label>Three</label>
</div>
<div class="checkboxmsg">Only two options are allowed</div>

You are almost there. Just need to toggle display of message box when limit reached
limit = 0; //set limit
checkboxes = document.querySelectorAll('.checkboxdiv input[type="checkbox"]'); //select all checkboxes
function checker(elem) {
if (elem.checked) { //if checked, increment counter
limit++;
} else {
limit--; //else, decrement counter
}
for (i = 0; i < checkboxes.length; i++) { // loop through all
if (limit == 2) {
if (!checkboxes[i].checked) {
checkboxes[i].disabled = true;
document.getElementsByClassName("checkboxmsg")[0].style.display = "block"
}
} else { //if limit is less than two
if (!checkboxes[i].checked) {
checkboxes[i].disabled = false; document.getElementsByClassName("checkboxmsg")[0].style.display = "none"
}
}
}
}
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].onclick = function() { //call function on click and send current element as param
checker(this);
}
}
.checkboxmsg{
display: none;
color : red !important;
}
<div class="checkboxdiv">
<input type="hidden" name="check" value="">
<input type="checkbox" name="check" value="One"><label>One</label> <br/>
<input type="checkbox" name="check" value="Two"><label>Two</label> <br/>
<input type="checkbox" name="check" value="Three"><label>Three</label>
</div>
<div class="checkboxmsg">Only two options are allowed</div>

Initially, hide the checkboxmsg div, then show it when the limit is reached, and hide it again if the count is lower.
Here is a function that would show / hide the div:
function toggleMessage(state) {
var display = state ? 'block' : 'none';
document.querySelector('.checkboxmsg').style.display = display;
}
Working demo:
limit = 0; //set limit
checkboxes = document.querySelectorAll('.checkboxdiv input[type="checkbox"]'); //select all checkboxes
function checker(elem) {
if (elem.checked) { //if checked, increment counter
limit++;
} else {
limit--; //else, decrement counter
}
for (i = 0; i < checkboxes.length; i++) { // loop through all
if (limit == 2) {
toggleMessage(true);
if (!checkboxes[i].checked) {
checkboxes[i].disabled = true; // and disable unchecked checkboxes
}
} else { //if limit is less than two
toggleMessage(false);
if (!checkboxes[i].checked) {
checkboxes[i].disabled = false; // enable unchecked checkboxes
}
}
}
}
function toggleMessage(state) {
var display = state ? 'block' : 'none';
document.querySelector('.checkboxmsg').style.display = display;
}
toggleMessage(false);
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].onclick = function() { //call function on click and send current element as param
checker(this);
}
}
<div class="checkboxdiv">
<input type="hidden" name="check" value="">
<label><input type="checkbox" name="check" value="One">One</label> <br/>
<label><input type="checkbox" name="check" value="Two">Two</label> <br/>
<label><input type="checkbox" name="check" value="Three">Three</label>
</div>
<div class="checkboxmsg">Only two options are allowed</div>

Hide the message with a class, and toggle via monitoring limit
limit = 0; //set limit
checkboxes = document.querySelectorAll('.checkboxdiv input[type="checkbox"]'); //select all checkboxes
msg = document.getElementById('msg');
function checker(elem) {
if (elem.checked) { //if checked, increment counter
limit++;
} else {
limit--; //else, decrement counter
}
if(limit == 2)
msg.classList.remove('hide');
else msg.classList.add('hide');
for (i = 0; i < checkboxes.length; i++) { // loop through all
if (limit == 2) {
if (!checkboxes[i].checked) {
checkboxes[i].disabled = true; // and disable unchecked checkboxes
}
} else { //if limit is less than two
if (!checkboxes[i].checked) {
checkboxes[i].disabled = false; // enable unchecked checkboxes
}
}
}
}
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].onclick = function() { //call function on click and send current element as param
checker(this);
}
}
.checkboxmsg.hide{
display: none
}
<div class="checkboxdiv">
<input type="hidden" name="check" value="">
<input type="checkbox" name="check" value="One"><label>One</label> <br/>
<input type="checkbox" name="check" value="Two"><label>Two</label> <br/>
<input type="checkbox" name="check" value="Three"><label>Three</label>
</div>
<div id="msg" class="checkboxmsg hide">Only two options are allowed</div>

limit = 0; //set limit
checkboxes = document.querySelectorAll('.checkboxdiv input[type="checkbox"]'); //select all checkboxes
function checker(elem) {
if (elem.checked) { //if checked, increment counter
limit++;
} else {
limit--; //else, decrement counter
}
for (i = 0; i < checkboxes.length; i++) { // loop through all
var ele = document.getElementById("toggleText");
if (limit == 2) {
if (!checkboxes[i].checked) {
checkboxes[i].disabled = true; // and disable unchecked checkboxes
}
ele.style.display = "block";
} else { //if limit is less than two
if (ele.style.display == "block") {
ele.style.display = "none";
}
if (!checkboxes[i].checked) {
checkboxes[i].disabled = false; // enable unchecked checkboxes
}
}
}
}
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].onclick = function() { //call function on click and send current element as param
checker(this);
}
}
<div class="checkboxdiv">
<input type="hidden" name="check" value="">
<input type="checkbox" name="check" value="One"><label>One</label> <br/>
<input type="checkbox" name="check" value="Two"><label>Two</label> <br/>
<input type="checkbox" name="check" value="Three"><label>Three</label>
</div>
<div id="toggleText" class="checkboxmsg" style="display: none">Only two options are allowed</div>

You can use innerHTML and querySelector to change the div checkboxmsg
limit = 0; //set limit
var checkboxmsg = document.querySelector('.checkboxmsg')
checkboxes = document.querySelectorAll('.checkboxdiv input[type="checkbox"]'); //select all checkboxes
function checker(elem) {
if (elem.checked) { //if checked, increment counter
limit++;
} else {
limit--; //else, decrement counter
}
for (i = 0; i < checkboxes.length; i++) { // loop through all
if (limit == 2) {
if (!checkboxes[i].checked) {
checkboxes[i].disabled = true; // and disable unchecked checkboxes
checkboxmsg.innerHTML = "Limit reached!"
}
} else { //if limit is less than two
if (!checkboxes[i].checked) {
checkboxes[i].disabled = false; // enable unchecked checkboxes
checkboxmsg.innerHTML = "Only two options are allowed"
}
}
}
}
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].onclick = function() { //call function on click and send current element as param
checker(this);
}
}
<div class="checkboxdiv">
<input type="hidden" name="check" value="">
<input type="checkbox" name="check" value="One"><label>One</label> <br/>
<input type="checkbox" name="check" value="Two"><label>Two</label> <br/>
<input type="checkbox" name="check" value="Three"><label>Three</label>
</div>
<div class="checkboxmsg">Only two options are allowed</div>

Related

How to do proper validation for this and set focus and then form has to submitted

Here I am facing problem in if condition it validates for subject and unable to set focus and not validate for medium field. Here checkbox is coming from mysql. But it gives source like this only. can any figure out what is the problem in my code?what I have to do here.I hope everyone understand the question.I need to proper code to validate these two fields. At least in subject column any one should be selected likewise in regional field also any should be selected. I tried has much what I can do. But I could not completed the work.
what I needed is:
Atleast any one should be selected in subject field.if its null alert +focus
like wise for medium field also.
<script type="text/javascript">
function check() {
var a1 = false;
b1 = false;
var chk = document.getElementsByName('subject[]');
var reg = document.getElementsByName('regional[]');
var len = chk.length;
var reg1 = reg.length;
if (len) {
for (i = 0; i < len; i++) {
if (chk[i].checked) {
return true;
} else {
alert('please select the subject');
a1 = true;
}
}
}
if (!chk[i].checked) {
chk[i].focus();
}
if (len) {
for (i = 0; i < len; i++) {
if (reg1[i].checked) {
return true;
} else {
alert('please select the medium');
b1 = true;
}
}
}
if (a1 == true && b1 == true) {
return true;
}
}
</script>
Myform is:
<form name="f1" action="s.php" method="post">
Subject
<input type='checkbox' name='subject[]' value='science'>science
<input type='checkbox' name='subject[]' value='maths'>maths<br/>
Medium
<input type='checkbox' name='regional[]' value='Hindi'>Hindi
<input type='checkbox' name='regional[]' value='english'>english<br/>
<input type="submit" name="land" class="butt" value="SUBMIT" onClick="return check();">
</form>
Like this
Instead of onclick use onsubmit and assign the function onload
window.onload=function() {
document.getElementsByName("f1")[0].onsubmit=function() {
var chk = document.getElementsByName('subject[]'),chkOk=false;
for (var i = 0, n=chk.length; i < n; i++) {
if (chk[i].checked) {
chkOk = true;
break;
}
}
console.log(chkOk)
if (!chkOk) {
alert('please select the subject');
chk[0].focus(); // focus the first
return false;
}
var reg = document.getElementsByName('regional[]'),regOk=false;
for (var i = 0, n=reg.length; i < n; i++) {
if (reg[i].checked) {
regOk = true;
break;
}
}
if (!regOk) {
alert('please select the medium');
reg[0].focus(); // focus the first
return false;
}
return true; // allow submit
}
}
<form name="f1" action="s.php" method="post" onsubmit="return check()">
Subject
<input type='checkbox' name='subject[]' value='science'>science
<input type='checkbox' name='subject[]' value='maths'>maths<br/>
Medium
<input type='checkbox' name='regional[]' value='Hindi'>Hindi
<input type='checkbox' name='regional[]' value='english'>english<br/>
<input type="submit" name="land" class="butt" value="SUBMIT">
</form>

getElementByTagName not working

When I click delete button without clicking any checkbox, it should show alert, but in this coding, if first checkbox checked, it doesn't show alert. If second checkbox checked, it show alert.
HTML:
<div id="checkbox">
<input type="CHECKBOX" name="MyCheckbox" class="checkbox" value="This..." >
<input type="CHECKBOX" name="MyCheckbox" class="checkbox" value="This..." >
<input type="CHECKBOX" name="MyCheckbox" class="checkbox" value="This..." >
<input type="CHECKBOX" name="MyCheckbox" class="checkbox" value="This..." >
</div>
<form action="DeleteServer" onsubmit="return checkCheckBoxes(this);">
<input type="SUBMIT" value="Delete!">
</form>
script function:
function checkCheckBoxes() {
var chk = document.getElementById("checkbox").getElementsByTagName("input");
for(var i=0; i<chk.length;i++){
if (document.getElementById("checkbox").getElementsByTagName("input")[i].checked == false)
{
alert ('You didn\'t choose any of the checkboxes!');
return false;
} else {
return true;
}
}
}
getElementsByTagName has an s in it. It is plural. It returns a NodeList not a single Element.
Given your HTML, that NodeList will include 2 separate inputs.
You have to loop over it (as if it was an Array) and test the checked property of each input in turn.
This should solve your problem:
var inputs = document.querySelectorAll('#checkbox input');
is_checked = false;
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type == 'checkbox' && inputs[i].name == 'MyCheckbox') {
is_checked = inputs[i].checked;
if(is_checked) break;
}
}
if(!is_checked){
alert('You didn\'t choose any of the checkboxes!');
}
Here is a fiddle
function checkCheckBoxes() {
var inputs = document.querySelectorAll('#checkbox input');
is_checked = false;
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type == 'checkbox') {
is_checked = inputs[i].checked;
if(is_checked) return true;
}
}
if(!is_checked){
alert('You didn\'t choose any of the checkboxes!');
return false;
}
}

Check boxes validation in JavaScript

I have written this script:
function getDays(select){
var selectedString = select.options[select.selectedIndex].value;
if(selectedString == 4)
{
document.getElementById("days_target").style.display = "block";
}else {
document.getElementById("days_target").style.display = "none";
}
}
and in validateForm() function I have this:
var x=document.forms["form1"]["days"].value;
if (x==null || x=="" || x=="Select Days")
{
alert("Oh, you forgot to select days! :)");
return false;
}
var x=document.forms["form1"]["days"].value;
if(x=="4")
{
var cnt = 0;
for (var i = 7; i < document.day.elements.length; i++) {
if (document.day.elements[i].type == 'checkbox') {
if (document.day.elements[i].checked == true) {
cnt++;
}
}
}
if (cnt == 0) {
alert("Atleast 1 day Should be Selected.");
return false;
}
}
HTML like this:
<b>Please enter days required</b><br/>
<select name="days" id="days" style="width:200px;" onchange="getDays(this)">
<option value="Select Days" selected>Select Days</option>
<option value="1">Mon-Fri</option>
<option value="2">Mon-Fri</option>
<option value="3">Mon-Fri</option>
<option value="4">Bespoke Days</option>
</select><br/><br/>
<div id="days_target" style="display:none;">
<b>Select Days</b><br/>
<input type="checkbox" name="day" value="mon"/>Mon <input type="checkbox" name="day" value="tue"/>Tue<br/>
<input type="checkbox" name="day" value="wed"/>Wed <input type="checkbox" name="day" value="thr"/>Thr<br/>
<input type="checkbox" name="day" value="fri"/>Fri <input type="checkbox" name="day" value="sat"/>Sat<br/>
<input type="checkbox" name="day" value="sun"/>Sun<br/><br/>
</div>
If I select Bespoke days then that check boxes appear and if none is checked then I want to display error message "Atleast one day should be selected." How to do this?
You are accessing the checkboxes incorrectly. Forms have elements. Also you start from 7 and count up instead of from 0 and count up or from 6 and count down
var day = document.forms["form1"].day;
for (var i = 0; i < day.length; i++) {
if (day[i].type == 'checkbox') {
if (day[i].checked == true) {
cnt++;
}
}
}
I would do it like this:
Live Demo
var x=document.forms["form1"]["days"].selectedIndex;
if (x<1) {
alert("Please select days");
return false;
}
else if(x==4) { // fifth entry
var checked = false, chk = document.forms["form1"]["day"];
for (var i = 0; i < chk.length; i++) {
if (chk[i].checked) { checked=true; break }
}
if (!checked) {
alert("At least one day should be checked.");
return false;
}
}
The after function in jquery would allow you to easily do this. This would require two steps.
Load Jquery by putting this inside your header tag in the HTML (<head></head>):
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Add javascript in the validation when the condition is not met:
$('#days').after('<label class="error">Atleast one day should be selected.</label.');
Additionally, you will want the error message to go away when the validation rules are met.
$('.error').remove();
You will probably want to adjust the HTML/CSS for displaying purposes, but that should be enough to get you going.

Javascript: master checkbox to control all checkboxes in a table column

I have 5 checkboxes. One of them is the header for all checkboxes. If I check the header checkbox, all should check automatically, and if I uncheck it, all should uncheck. If I uncheck any of the child checkboxes, the header should automatically uncheck.
My code is like this:
<html>
<SCRIPT LANGUAGE="JavaScript">
function checkAll()
{
if(pp_checkall.checked==true)
{
for (i = 1; i <= pp_check.length; i++)
pp_check[i].checked = true ;
}
else
{
for (i = 1; i <= pp_check.length; i++)
pp_check[i].checked = false ;
}
}
</script>
<SCRIPT LANGUAGE="JavaScript">
function checkOne()
{
for (i = 1; i <= pp_check.length; i++)
{
if(pp_check[i].checked==false)
{
pp_checkall.checked = false ;
}
}
}
</script>
<body>
<table>
<tr><th width="1px"><input type="checkbox" text="Dharan" name="pp_checkall" onclick="checkAll();"></th></tr>
<tr>
</tr>
<tr> <input type="checkbox" name="pp_check" value="1" onclick="checkOne();"></tr>
<!--<tr> <input type="checkbox" name="pp_check" value="2" onclick="checkOne();"></tr>
<tr> <input type="checkbox" name="pp_check" value="3" onclick="checkOne();"></tr>
<tr> <input type="checkbox" name="pp_check" value="4" onclick="checkOne();"></tr> -->
</table>
</body>
</html>
Its working fine too, but in some cases only one <td> checkbox will appear, which stops the code from working. Please give some solution to solve this.
Try this
<script type="text/javascript" language="javascript">
var pp_check = document.getElementsByName('pp_check');
var pp_checkall = document.getElementsByName('pp_checkall')[0];
function checkAll() {
if (pp_checkall.checked == true) {
for (i = 0; i < pp_check.length; i++)
pp_check[i].checked = true;
}
else {
for (i = 0; i < pp_check.length; i++)
pp_check[i].checked = false;
}
}
function checkOne() {
var pp_check = document.getElementsByName('pp_check');
for (i = 0; i < pp_check.length; i++) {
if (pp_check[i].checked == false)
pp_checkall.checked = false;
}
}
</script>
You can use jQuery for the same.
$('input[name="pp_checkall"]').change(function () {
$('input[name=pp_check]').attr('checked', this.checked);
});
$('input[name="pp_check"]').change(function () {
$('input[name="pp_checkall"]').prop(
'checked',
$('input[name=pp_check]:not(:checked)').length === 0 ? true : false
);
});
Demo: http://jsfiddle.net/gPeh8/1/

Javascript Internet Explorer Issue - what am I doing wrong?

I've looked through many posts to no avail. I have the following in a simple form where one of the products changes based on the number of checkboxes checked. It works in every browser except IE. What am I doing wrong?
<body>
<script type="text/javascript">
function check(){
"use strict";
var count = 0, x=0, checkboxes=document.signup.getElementsByClassName("styled");
for(;x<checkboxes.length; x++){
if(checkboxes[x].checked){
count++;
}
}
if(count<3) {
document.getElementById("variable").value = "1";
}
else if (count == 3){
document.getElementById("variable").value = "74";
}
else if (count == 4){
document.getElementById("variable").value = "75";
}
else if (count == 5){
document.getElementById("variable").value = "76";
}
}
</script>
<form name="signup" id="signup" method="post" action="/subscribers/signup.php">
<input type="checkbox" id="variable" name="product_id[]" value="" class="styled"></input>product 1 - variable</div>
<input type="checkbox" id="same" name="product_id[]" value="3" class="styled"></input>product 2
<input type="checkbox" id="same2" name="product_id[]" value="2" class="styled"></input>product 3
<input type="checkbox" id="same3" name="product_id[]" value="4" class="styled"></input><div class="check-title">product 4
<input type="checkbox" id="same4" name="product_id[]" value="44" class="styled"></input><div class="check-title">product 5
Continue</td></tr>
</form>
</body>
All versions of IE prior to IE9 do not support getElementsByClassName(). You will need to use some sort of substitute.
Instead of this piece of your code:
checkboxes = document.signup.getElementsByClassName("styled");
I would suggest using this:
checkboxes = document.getElementById("signup").getElementsByTagName("input")
getElementsByTagName() is widely support in all versions of IE. This will obviously get all input tags, but only the checkboxes will have checked set so you should be OK.
If you need to filter by class, then you could do the whole thing this way:
function check() {
"use strict";
// initialize checkbox count to 0
var count = 0, item;
// get all input tags in the form
var inputs = document.getElementById("signup").getElementsByTagName("input");
// loop through all input tags in the form
for (var i = 0; i < inputs.length; i++) {
// get this one into the local variable item
item = inputs[i];
// if this input tag has the right classname and is checked, increment the count
if ((item.className.indexOf("styled") != -1) && item.checked) {
count++;
}
}
// get object for result
var obj = document.getElementById("variable");
// check count and set result based on the count
if(count < 3) {
obj.value = "1";
} else if (count == 3) {
obj.value = "74";
} else if (count == 4) {
obj.value = "75";
} else if (count == 5) {
obj.value = "76";
}
}
IE doesnt have method getElementsByClassName... you can try to define it:
if(document.getElementsByClassName == undefined) {
document.getElementsByClassName = function(cl) {
var retnode = [];
var myclass = new RegExp('\\b'+cl+'\\b');
var elem = this.getElementsByTagName('*');
for (var i = 0; i < elem.length; i++) {
var classes = elem[i].className;
if (myclass.test(classes)) {
retnode.push(elem[i]);
}
}
return retnode;
}
};

Categories