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;
}
}
Related
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>
I would like to ask for help with function that merge checkboxes into one field. In question Combine checkbox values into string before submitting form I have found one but I would like it to start onsubmit with another function that checks if the form was filled correctlty.
Form:
<form id="formularz_wspolpraca" name="Zapis na poradnik" method="post" target="_top" onsubmit="return SprawdzFormularz(this) && mergeFunction(this)">
<input type="text" id="email" name="email"/>
<input type="text" id="imie" name="imie"/>
<input type="text" id="nazwisko" name="nazwisko"/>
<input type="text" maxlength="12" size="12" id="pole_1" name="pole_1"/>
<input class="checkbox_wspolpraca" type="Checkbox" name="pole_3a" value="polecajacy">
<input class="checkbox_wspolpraca" type="Checkbox" name="pole_3b" value="projektant">
<input class="checkbox_wspolpraca" type="Checkbox" name="pole_3c" value="instalator">
<input class="checkbox_wspolpraca" type="Checkbox" name="pole_3d" value="ekspert">
<input type="hidden" name="pole_3" id="pole_3">
<input id="pp" type="checkbox" name="pp" checked=""/>
<input type="submit" value="WyĆlij">
</form>
Merge function:
function mergeFuntion(event) {
event.preventDefault();
var boxes = document.getElementsByClassName('checkbox_wspolpraca');
var checked = [];
for (var i = 0; boxes[i]; ++i) {
if (boxes[i].checked) {
checked.push(boxes[i].value);
}
}
var checkedStr = checked.join(' ');
document.getElementById('pole_3').value = checkedStr;
return true;
}
Check function:
function SprawdzFormularz(f) {
if (f.email.value == "") {
alert("Nie poda\u0142e\u015b/a\u015b adresu e-mail.");
return false;
}
if (((f.email.value.indexOf("#", 1)) == -1) || (f.email.value.indexOf(".", 1)) == -1) {
alert("Poda\u0142e\u015b/a\u015b b\u0142\u0119dny adres e-mail.");
return false;
}
if (f.imie.value == "") {
alert("Wype\u0142nij pole Imi\u0119. ");
return false;
}
if (f.nazwisko.value == "") {
alert("Wype\u0142nij pole Nazwisko. ");
return false;
}
if (f.pole_1.value == "") {
alert("Wype\u0142nij pole Nr telefonu. ");
return false;
}
if ((f.pole_3a.checked == false) && (f.pole_3b.checked == false) && (f.pole_3c.checked == false) && (f.pole_3d.checked == false)) {
alert("Wybierz zakres wsp\u00f3\u0142pracy");
return false;
}
if (f.pp.checked == false) {
alert("Musisz zgodzi\u0107 si\u0119 z Polityk\u0105 Prywatno\u015bci.");
return false;
}
return true;
}
Check function is working without a problem but i can't get merge one to work as well. Can someone point out what am I doing wrong with merge function? I'm quite new to javascript so that could be some rookie mistake. Thanks in advance.
In onsubmit you are running SprawdzFormularz first and it returns true if all the checks pass. This means that it will submit the form, before the merge function is run.
You need to run the merge function inside the check function before returning true so that the form does not submit before you have combined the string and set the necessary value.
function SprawdzFormularz(f) {
// ....
var boxes = document.getElementsByClassName('checkbox_wspolpraca');
var checked = [];
for (var i = 0; boxes[i]; ++i) {
if (boxes[i].checked) {
checked.push(boxes[i].value);
}
}
var checkedStr = checked.join(' ');
document.getElementById('pole_3').value = checkedStr;
return true;
}
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>
Ok i have multy fields with same name, and i want to check is all fields are not empty. My code works if i have only one input, but i have no idea how to do that with more inputs
<input class = "new_input" type=text name="name[]"/>
<input class = "new_input" type=text name="name[]"/>
function validation(){
var x = document.forms["form"]["name"].value;
if(x ==='')
{
$("#warning").html("Morate uneti vrednost!").css('color','red');
return false;
}
else
{
return true;
}
}
for example if enter only one field, validation will work, and i want to check all fields
Using just JS you could do something like
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<button onclick="validate()">Validate</button>
<script type="text/javascript">
function validate() {
var inputs = document.getElementsByTagName("input");
var empty_inputs = 0;
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('name') == 0) { // check all inputs with 'name' in their name
if (inputs[i].value == '') {
empty_inputs++;
console.log('Input ' + i + ' is empty!');
}
}
}
if (empty_inputs == 0) {
console.log('All inputs have a value');
}
}
</script>
You have tagged jquery, so I have given something which works in jquery
http://jsfiddle.net/8uwo6fjz/1/
$("#validate").click(function(){
var x = $("input[name='name[]']")
$(x).each(function(key,val){
if($(val).val().length<=0)
{
$("#warning").html("Morate uneti vrednost!").css('color','red');
}
});
});
Try this:
function validate(){
var error = 0;
$.each( $("input[name='name[]']"), function(index,value){
if( value.value.length == 0){
$("#warning").html("Morate uneti vrednost!").css('color','red');
error = 1;
return;
}
});
if(!error){
$("#warning").html("");
}
}
Check it out here: jsFiddle
I am available with the solution given by #Tomalak for MY QUESTION could you pls help me out with it as its giving me an error in firebug as : frm.creatorusers is undefined
[Break On This Error] var rdo = (frm.creatorusers.length >...rm.creatorusers : frm.creatorusers;
I used the code for validating radio button as:
function valDistribution(frm) {
var mycreator = -1;
var rdo = (frm.creatorusers.length > 0) ? frm.creatorusers : frm.creatorusers;
for (var i=0; i<rdo.length; i++) {
if (rdo[i].checked) {
mycreator = 1;
//return true;
}
}
if(mycreator == -1){
alert("You must select a Creator User!");
return false;
}
}
Here is how to use the code you were given by #Tomalak but did not copy correctly
function valDistribution(frm) { // frm needs to be passed here
var myCreator=false;
// create an array if not already an array
var rdo = (frm.creatorusers.length > 0) ? frm.creatorusers : [frm.creatorusers];
for (var i=0; i<rdo.length; i++) {
if (rdo[i].checked) {
myCreator=true;
break; // no need to stay here
}
if (!myCreator){
alert("You must select a Creator User!");
return false;
}
return true; // allow submission
}
assuming the onsubmit looking EXACTLY like this:
<form onsubmit="return valDistribution(this)">
and the radio NAMED like this:
<input type="radio" name="creatorusers" ...>
You can try this script:
<html>
<script language="javascript">
function valbutton(thisform) {
myOption = -1;
alert(thisform.creatorusers.length);
if(thisform.creatorusers.length ==undefined) {
alert("not an array");
//thisform.creatorusers.checked = true;
if(thisform.creatorusers.checked) {
alert("now checked");
myOption=1;
alert("You selected button number " + myOption
+ " which has a value of "
+ thisform.creatorusers.value);
}
}
else {
for (i=thisform.creatorusers.length-1; i > -1; i--) {
if (thisform.creatorusers[i].checked) {
myOption = i; i = -1;
}
}
if (myOption == -1) {
alert("You must select a radio button");
return false;
}
alert("You selected button number " + myOption
+ " which has a value of "
+ thisform.creatorusers[myOption].value);
}
}
</script>
<body>
<form name="myform">
<input type="radio" value="1st value" name="creatorusers" />1st<br />
<!--<input type="radio" value="2nd value" name="creatorusers" />2nd<br />-->
<input type="button" name="submitit" onclick="valbutton(myform);return false;" value="Validate" />
<input type="reset" name="reset" value="Clear" />
</form>
</body>
</html>