I have a problem in validating whether at least one checkbox is checked or not.
The same code is being used for a different form and its working perfectly but I can't figure why it doesn't on this form.
Script:
if(jQuery('#MOTForm input[type=checkbox]:checked').length == 0) {
alert("1");
valid = valid && false;
$("#MOTFORMERROR").css('color', 'red');
$("#MOTFORMERROR").html("*Choose at least one");
}else{
$("#MOTFORMERROR").html("");
}
Html:
<td style="width: 10%;" rowspan="3">
<div style="padding-left:5px;">
<form id="MOTForm">
<input name="" type="checkbox" class="form-check-input"/> HEMS<br />
<input name="" type="checkbox" class="form-check-input"/> EMS<br />
<input name="" type="checkbox" class="form-check-input"/> Walk-in<br />
</form>
<p id="MOTFORMERROR"></p>
</div>
</td>
The code in the block of the if statement is being run all the time, instead of the code in the block of the else statement, even if one or all checkboxes are checked!
your code does not show when the javascript is executed, maybe your checkboxes are not yet rendered when you look for them.
In fact if you run your code in the exact order you posted here is perfectly normal that your condition is always true.
If you put your code inside a function to be called after all the HTML is rendered everything works perfectly:
<td style="width: 10%;" rowspan="3">
<div style="padding-left:5px;">
<form id="MOTForm">
<input name="" type="checkbox" class="form-check-input"/> HEMS<br />
<input name="" type="checkbox" class="form-check-input"/> EMS<br />
<input name="" type="checkbox" class="form-check-input"/> Walk-in<br />
</form>
<p id="MOTFORMERROR"></p>
</div>
</td>
<!-- ... -->
<button id="check_btn">Click me</button>
<!-- ... -->
<script>
var valid;
$('#check_btn').click(function() {
if ($('#MOTForm input[type=checkbox]:checked').length == 0) {
valid = false;
$("#MOTFORMERROR").css('color', 'red');
$("#MOTFORMERROR").html("*Choose at least one");
} else {
$("#MOTFORMERROR").html("");
}
});
</script>
Since the variable valid wasn't defined, there was an error in your initial code (see below). This error is visible in the browser console.
Uncaught ReferenceError: valid is not defined
Because of that error, the lines after valid = valid && false; are not being executed.
To fix this, declare that variable before this code is run:
var valid = false;
//...other code to check if form is valid
Then move the original JavaScript code into a function that can be run on submit (e.g. function check() {...}). See this demonstrated below. It uses the jQuery function .click() to bind the event handler to the submit button. You will also notice it uses .ready() to wait until the DOM is ready before binding the event handler to the submit button.
//wait until DOM is ready to bind check function to button click
$(document).ready(function(readyEvent) {
$('#submit').click(check);
})
var valid = false;
function check() {
if (jQuery('#MOTForm input[type=checkbox]:checked').length == 0) {
alert("1");
valid = valid && false;
$("#MOTFORMERROR").css('color', 'red');
$("#MOTFORMERROR").html("*Choose at least one");
} else {
console.log('no error- clearing error html');
$("#MOTFORMERROR").html("");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="padding-left:5px;">
<form id="MOTForm">
<input name="" type="checkbox" class="form-check-input" /> HEMS
<br />
<input name="" type="checkbox" class="form-check-input" /> EMS
<br />
<input name="" type="checkbox" class="form-check-input" /> Walk-in
<br />
<button id="submit">
Submit
</button>
</form>
<p id="MOTFORMERROR"></p>
</div>
Update:
You typed a comment on your post (replying to questions in other comments):
valid is declared at the beginning of .click
Now that that information is revealed, it makes me feel like most of what I said above is useless. Moving the declaration of valid into the click handler seems like a trivial change and there isn't much different besides that... See the example below:
//wait until DOM is ready to bind check function to button click
$(document).ready(function(readyEvent) {
$('#submit').click(check);
})
function check() {
var valid = false;
if (jQuery('#MOTForm input[type=checkbox]:checked').length == 0) {
alert("1");
valid = valid && false;
$("#MOTFORMERROR").css('color', 'red');
$("#MOTFORMERROR").html("*Choose at least one");
} else {
console.log('no error- clearing error html');
$("#MOTFORMERROR").html("");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="padding-left:5px;">
<form id="MOTForm">
<input name="" type="checkbox" class="form-check-input" /> HEMS
<br />
<input name="" type="checkbox" class="form-check-input" /> EMS
<br />
<input name="" type="checkbox" class="form-check-input" /> Walk-in
<br />
<button id="submit">
Submit
</button>
</form>
<p id="MOTFORMERROR"></p>
</div>
Please have a look at the following snippet. It does that you are looking for. I removed the valid variable, since it isn't apparent, where this parameter is used. Apparently, you can add it and use it as you think.
$(function(){
function checkCheckBoxes(){
if($('#MOTForm input[type=checkbox]:checked').length == 0) {
alert("1");
$("#MOTFORMERROR").css('color', 'red');
$("#MOTFORMERROR").html("*Choose at least one");
} else {
$("#MOTFORMERROR").html("");
}
}
$(".js-check").on("change", checkCheckBoxes);
checkCheckBoxes();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td style="width: 10%;" rowspan="3">
<div style="padding-left:5px;">
<form id="MOTForm">
<input name="" type="checkbox" class="form-check-input js-check"/> HEMS<br />
<input name="" type="checkbox" class="form-check-input js-check"/> EMS<br />
<input name="" type="checkbox" class="form-check-input js-check"/> Walk-in<br />
</form>
<p id="MOTFORMERROR"></p>
</div>
</td>
Related
I have 2 checkboxes. I need one, not both, but at least 1 to be checked. It is not a multiple selection but zero is not accepted. If one is checked, this line will work jQuery('#wiz_menu.nav-tabs > .active').next('li').find('a').trigger('click'); otherwise it should alert. The following makes it alerting all the time.
UPDATE
I am not using the submit button or I would have used the validate plugin. It is a normal button to go next in the wizard <button type="button" class="btnNext">Next step</button>
HTML
<div class="form-group">
<label for="usp-category-8" class="usp-checkbox usp-cat usp-cat-0">
<input type="checkbox" name="usp-category[]" id="usp-category-8" value="8" data-required="true" class="usp-input usp-input-category">
Cultura
</label>
<label for="usp-category-7" class="usp-checkbox usp-cat usp-cat-0">
<input type="checkbox" name="usp-category[]" id="usp-category-7" value="7" data-required="true" class="usp-input usp-input-category">
Scienze
</label>
<input type="hidden" name="usp-category-required" value="1">
</div>
JS
jQuery('.btnNext').on("click", function(){
if(jQuery(".tab-pane").is("#step1")) {
var isChecked = false;
$('input[type=checkbox]').on("change", function () {
isChecked = true;
});
if ( isChecked ) {
jQuery('#wiz_menu.nav-tabs > .active').next('li').find('a').trigger('click');
} else {
alert( 'Please, check at least one checkbox!' );
}
}
});
With jQuery you can use is:
$('#form').on('submit', function(e) {
e.preventDefault();
if ($('input[name="hi"]').is(':checked')) {
console.log('checked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<input type="checkbox" name="hi" value="hi">Hallo<br>
<input type="checkbox" name="gb" value="gb">Tschuss<br>
<input type="submit" value="Submit">
</form>
Adapted to your code:
$('.btnNext').click(function(e) {
e.preventDefault();
if ($('#usp-category-7').is(':checked') || $('#usp-category-8').is(':checked')) {
console.log('at least one is checked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="usp-category-8" class="usp-checkbox usp-cat usp-cat-0">
<input type="checkbox" name="usp-category[]" id="usp-category-8" value="8" data-required="true" class="usp-input usp-input-category">
Cultura
</label>
<label for="usp-category-7" class="usp-checkbox usp-cat usp-cat-0">
<input type="checkbox" name="usp-category[]" id="usp-category-7" value="7" data-required="true" class="usp-input usp-input-category">
Scienze
</label>
<input type="hidden" name="usp-category-required" value="1">
<button class="btnNext">Next</button>
</div>
Thanks to a comment, I personally resolved it like this, making them radio buttons. But I will accept the other answer as it is correct.
jQuery('.btnNext').on("click", function(){
if(jQuery(".tab-pane").is("#step1")) {
if($('input[type=radio').is(':checked')) {
jQuery('#wiz_menu.nav-tabs > .active').next('li').find('a').trigger('click');
} else {
alert( 'Please, check at least one checkbox!' );
}
}
});
I think my brain has already checked out and is in holiday mode. I'm trying to do something extremely simple, and I can not get it to work for the life of me.
I have a form that is dynamically generated via server-side code. It can have one or more questions that have checkboxes as options. I need to check to make sure at least one item is checked in any group, and the validation has to be done in pure JS (no jQuery).
I'm banging my head against the desk trying to get it to work:
HTML:
<form onsubmit="return validateCheckboxes();">
<h4>Which things do you enjoy?</h4>
<input type='checkbox' name='2' value='12' id='2_12'>
<label for='2_12'> Breathing</label><br />
<input type='checkbox' name='2' value='13' id='2_13'>
<label for='2_13'> Watching paint dry</label><br />
<input type='checkbox' name='2' value='14' id='2_14'>
<label for='2_14'> Nothing</label><br />
<br />
<br />
<input type="button" value="Submit">
Javascript:
function validateCheckboxes() {
if (document.querySelector('.2:checked')) {
alert('something is checked');
return true;
} else {
alert('NOTHING is checked');
return false;
}
};
jsFiddle Link: https://jsfiddle.net/r6c4hxhj/
The selector .2:checked is looking for class="2" in the checkboxes. To select checkboxes with name="2" you should use
document.QuerySelector('[name="2"]:checked')
function validateCheckboxes() {
if (document.querySelector('[name="2"]:checked')) {
alert('something is checked');
return true;
} else {
alert('NOTHING is checked');
return false;
}
};
<form onsubmit="return validateCheckboxes();">
<h4>Which things do you enjoy?</h4>
<input type='checkbox' name='2' value='12' id='2_12'>
<label for='2_12'> Breathing</label><br />
<input type='checkbox' name='2' value='13' id='2_13'>
<label for='2_13'> Watching paint dry</label><br />
<input type='checkbox' name='2' value='14' id='2_14'>
<label for='2_14'> Nothing</label><br />
<br />
<br />
<input type="submit" value="Submit">
</form>
With .2:checked you are testing against the class whereas 2 is the name value. Add class=2 to your checkboxes.
The form element needed a closing tag </form>
The button needs to be a submit <input type="submit"/>
In order to get a HTMLCollection, use:
var chkList = document.querySelectorAll('input[type="checkbox"]:checked');
Then use a simple conditional against the collection's length:
if (chkList.length > 0)
http://plnkr.co/edit/PXiQCk0f7Qu3H5EYIgOF?p=preview
function validateCheckboxes() {
var chkList = document.querySelectorAll('input[type="checkbox"]:checked');
if (chkList.length > 0) {
alert('something is checked');
return true;
} else {
alert('NOTHING is checked');
return false;
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<form onsubmit="return validateCheckboxes();" action="http://examples.funwebdev.com/process.php" method="post">
<fieldset>
<legend>Which things do you enjoy?</legend>
<input type='checkbox' name='2' value='12' id='2_12'>
<label for='2_12'> Breathing</label>
<br />
<input type='checkbox' name='2' value='13' id='2_13'>
<label for='2_13'> Watching paint dry</label>
<br />
<input type='checkbox' name='2' value='14' id='2_14'>
<label for='2_14'> Nothing</label>
<br />
<br />
<br />
<input type="submit" value="Submit">
</fieldset>
</form>
</body>
</html>
you could iterate over each checkbox to see if it is checked on submission.
cool I just learnt something, I didn't realize you could use pseudo selectors with querySelectorAll. I still think this is a valid pattern though, if you want to compare the total checked with the total checkboxes to make it more dynamic. without another expensive querySelector attribute call.
function validateCheckboxes( form ){
var checkboxes = slice( form.querySelectorAll('[type=checkbox]') ),
ret = checkboxes.reduce( function( total, checkbox ){
if( checkbox.checked ){
++total;
}
return total;
}, 0 );
console.log( ret + ' of ' + checkboxes.length + ' checkboxes checked' );
return false; // to cancel submission for stack
}
function slice( arr, start ){
return Array.prototype.slice.call( arr, start || 0 );
}
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
<form onsubmit="return validateCheckboxes(this);">
<h4>Which things do you enjoy?</h4>
<input type='checkbox' name='2' value='12' id='2_12'>
<label for='2_12'> Breathing</label><br />
<input type='checkbox' name='2' value='13' id='2_13'>
<label for='2_13'> Watching paint dry</label><br />
<input type='checkbox' name='2' value='14' id='2_14'>
<label for='2_14'> Nothing</label><br />
<br />
<br />
<input type="submit" value="Submit">
Hello and thanks in advance for any help
In my store page, I have a checkbox that is checked when user agrees with the terms. When he checks the checkbox, submit button is disabled (false). My problem is that this solution doesn't work on iPhone and other mobile devices.
Here's the code:
function terms() {
if (document.getElementById("cbTerms").checked)
document.getElementById("submit").disabled = false;
else
document.getElementById("submit").disabled = true;
}
function cbc() {
if (document.getElementById("cbc").checked)
document.getElementById("cbc") = ("הריני מאשר קבלת מבצעים והטבות אל הדואר האלקטרוני מפראיה");
else
document.getElementById("cbc").value = ".";
}
<input class="btn btn-toranj alt" name="submit" type="submit" id="submit" value="לרכישה" disabled="true">
<br>
<br>
<input type="checkbox-0" id="cbTerms" name="cbTerms" onclick="terms();" style="width:15px; height:15px;">
<p style="margin-bottom:0px; font-size:14px; display: -webkit-inline-box;">הריני מאשר כי קראתי את התקנון
</p>
<br>
<input type="checkbox" id="cbc" name="os3" oninput="cbc()" style="width:15px; height:15px;">
<p style="margin-bottom:0px; font-size:14px; display: -webkit-inline-box;">הריני מאשר קבלת מבצעים והטבות אל דואר האלקטרוני</p>
<input type="hidden" value="הטבות ומבצעים" id="on3" name="on3">
At first sight your first checkbox is not really a checkbox.
<input type="checkbox-0" ...> should be more like: <input type="checkbox" ...>
With this change it will work.
P.S.:
Consider using braces for your if() {} else {} statements as you will propably run into some logic error if you change something in the future (e.g. add a line of code) and forget to add them.
The change event is preferred over click. And in addition, you'd pass the currently clicked checkbox on the fly as following
<input class="btn btn-toranj alt" name="submit" type="submit" id="submit" value="לרכישה" disabled="true">
<br><br>
<input type="checkbox" id="cbTerms" name="cbTerms" onchange="terms(this);" style="...">
<p style="...">הריני מאשר כי קראתי את
התקנון
</p>
<br>
<input type="checkbox" id="cbc" name="os3" onchange="cbc(this)" style="...">
<p style="...">הריני מאשר קבלת מבצעים והטבות אל דואר האלקטרוני</p>
<input type="hidden" value="הטבות ומבצעים" id="on3" name="on3">
<script type="text/javascript">
function terms(me)
{
document.getElementById("submit").disabled = !me.checked;
}
function cbc(me){
var val=document.getElementById("cbc").checked?
"הריני מאשר קבלת מבצעים והטבות אל הדואר האלקטרוני מפראיה":".";
document.getElementById("cbc").value = val;
}
</script>
I am trying to implement a script that will enable a submit button once a check-box is checked.
I am following an example found here: http://jsfiddle.net/chriscoyier/BPhZe/76/
I have added the following java-script code to my page but it doesn't seem like the script is executing properly. I do not see any errors in the console however.
<!---JQuery Iniialization --->
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script>
$( document ).ready(function() {
var checkboxes = $("input[type='checkbox']"),
submitButt = $("input[type='submit']");
checkboxes.click(function() {
submitButt.attr("disabled", !checkboxes.is(":checked"));
});
});
</script>
Form Code:
<FORM ACTION="signature_action.cfm?ticket_id=#url.ticket_id#&device=pc" METHOD=POST NAME="SigForm">
<div align="center">
<h2>STEP 1</h2>
<strong>Select the type of signature that is being captured:</strong><br />
<table><tr><td align="left">
<div id="format">
<input name="equipment_dropped_off" type="checkbox" id="check1" value="equipment_dropped_off" />
<label for="check1"><span class="style1">Equipment Dropped Off </span></label>
<span class="style1">
<input name="work" type="checkbox" id="check2" value="work"/>
<label for="check2">Work performed </label>
<input name="payment" id="check3" type="checkbox" value="payment" />
<label for="check3">Payment Recieved </label>
<input name="equipment_picked_up" id="check4" type="checkbox" value="equipment_picked_up" />
<label for="check4">Equipment Picked Up</label>
</span><br />
<input name="tech_name" type="hidden" value="#url.tech_name#">
</div>
<input name="hidden" type="hidden" value="#url.tech_name#">
<input type="submit" name="submit" value="STEP 4 - SAVE SIGNATURE" disabled>
</form>
I am new to javascript and I am strugling a bit. Doesn't this need to run once the DOM is ready? (I am not sure how to do that!)
Can someone point me in the right direction?
As per this article: How to add onDomReady to my document?, I put my code inside:
window.onload = function() {
//code here
}
The event that must be listened is "change".
$( document ).ready(function() {
var checkboxes = $("input[type='checkbox']"),
submitButt = $("input[type='submit']");
checkboxes.on('change', function() {
submitButt.attr('disabled', !this.checked);
});
});
I have a div that is hidden by inline styling on a form. I would like to have the div display when a user checks the "Other" checkbox. Would someone look at my code? It does not work. I think it might be do to my markup, but if it is the javascript code, let me know. Thank you for any help.
html:
<div class="item">
<label>How did you hear about us? <span class="req">*</span></label>
<br />
<input type="checkbox" value="Newspaper" id="CAT_Custom_510976_0" name="CAT_Custom_510976" />
Newspaper<br />
<input type="checkbox" value="Direct Mail" id="CAT_Custom_510976_1" name="CAT_Custom_510976" />
Direct Mail<br />
<input type="checkbox" value="Radio" id="CAT_Custom_510976_2" name="CAT_Custom_510976" />
Radio<br />
<input type="checkbox" value="Billboard" id="CAT_Custom_510976_3" name="CAT_Custom_510976" />
Billboard<br />
<input type="checkbox" value="Online Search" id="CAT_Custom_510976_4" name="CAT_Custom_510976" />
Online Search<br />
<input type="checkbox" value="Friend" id="CAT_Custom_510976_5" name="CAT_Custom_510976" />
Friend<br />
<input type="checkbox" value="Social Media" id="CAT_Custom_510976_6" name="CAT_Custom_510976" />
Social Media<br />
<input type="checkbox" value="Other..." id="CAT_Custom_510976_7" name="CAT_Custom_510976" />
Other...
</div>
<div style="display: none;" id="other" class="item">
<label for="CAT_Custom_510977">Other:</label>
<br />
<textarea onKeyDown="if(this.value.length>=4000)this.value=this.value.substring(0,3999);" class="cat_listbox" rows="4" cols="10" id="CAT_Custom_510977" name="CAT_Custom_510977"></textarea>
</div>
Javascript:
// Hide or show textarea if the other checkbox field is checked
var voucher = document.getElementById("CAT_Custom_510976_7");
function ShowCCFields(val) {
if (!document.getElementById('other'))
return;
if (voucher.checked == true)
document.getElementById('other').style.display = 'inline';
else{
document.getElementById('other').style.display = 'none';
}
}
You never actually call the function you created. To make your function run when the checkbox is clicked you should change your javascript to:
var voucher = document.getElementById("CAT_Custom_510976_7");
voucher.addEventListener('click', ShowCCFields);
function ShowCCFields(val) {
if (!document.getElementById('other'))
return;
if (voucher.checked == true)
document.getElementById('other').style.display = 'inline';
else{
document.getElementById('other').style.display = 'none';
}
}
The line addEventListener is what then allows the function to run when you the voucher is clicked.
You never actually assign the function to be called.
voucher.onchange = ShowCCFields;
Also, remove the val that's in the parentheses, since you don't appear to be using it.