how to adapt this script to include a checkbox check if checked - javascript

I'm a total noob at javascript. I use this script between my head tags that will force the user to scroll through a textarea before hitting submit button
<script language="JavaScript">
<!--
function textareaAtEnd(textareaObj)
{
return ((textareaObj.scrollTop + textareaObj.offsetHeight) > textareaObj.scrollHeight);
}
function formValidation(formObj)
{
if (textareaAtEnd(formObj.licenseAgreement))
{
return true;
} else {
alert ("Please scroll to the end to move on.")
return false;
}
}
// -->
</script>
my <form> looks like this:
<form action="step2.php" method="post" onSubmit="return formValidation(this);">
<textarea name="licenseAgreement" rows="20" cols="90">Very long license agreement text</textarea>
<br />
<input name="agree" type="checkbox" value="yes" /> I have read and agreed the above license agreement
<br />
<input type="submit" value="CONTINUE">
</form>
How can I adapt this javascript to also check if <input name="agree" type="checkbox" value="yes" /> is checked and if not to echo a message to the user? I'm a total noob, it's my first time using javascript.

do
function formValidation(formObj) {
if(!formObj.agree.checked) {
alert ("Please agree to terms.")
return false;
} else if (textareaAtEnd(formObj.licenseAgreement)) {
return true;
} else {
alert ("Please scroll to the end to move on.")
return false;
}
}
Demo: Fiddle

Use the checked property :
var checkbox = document.getElementsByName("agree")[0];
if(checkbox.checked)
alert("Check that");

Here you go:
if (document.getElementById('agree').checked == false) {
alert('Check the agree box dummy!');
}
Using ID's is a best practice I would always recommend using for client-side code.
So you would change your validation function to:
function formValidation() {
if (textareaAtEnd(document.getElementById('licenseAgreement')) == false) {
alert ("Please scroll to the end to move on.")
return false;
}
else if (document.getElementById('agree').checked == false) {
alert('Check the agree box dummy!');
return false;
}
else {
return true;
}
}
Also be sure to add an id="agree" to your <input type="checkbox" and id="licenseAgreement" to your textarea...
So it should look like this:
<input name="agree" id="agree" type="checkbox" value="yes" />
...
<textarea name="licenseAgreement" id="licenseAgreement" rows="20" cols="90">
And your form tag, you can remove the this parameter:
onSubmit="return formValidation();"

Replace
<input name="agree" type="checkbox" value="yes" />
With
<input name="agree" id="agree" type="checkbox" value="yes" />
Add id=agree attribute for checkbox.
if(document.getElementById("agree").checked == false)
{
alert("Checkbox is not checked , please select checkbox");
}

Related

How to disable/enable submit button depending on checkbox state?

There's a form with two text fields and one checkbox, all of them are required and have the required attribute.
The submit button should only get enabled if the required inputs are filled and checked.
With the current code the text field validation seems to work fine however it doesn't have an effect on the checkbox.
Jsfiddle
<form action="#otherForm">
Name * <input name="otherForm-name1" placeholder="required" required> <br />
Tel * <input name="otherForm-surname" placeholder="required" required> <br />
<input type="checkbox" name="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
<button id="otherForm-submitBtn" class="monitored-btn" type="submit">Submit</button>
</form>
<script>
const inputSelector = ':input[required]:visible';
function checkForm() {
// here, "this" is an input element
var isValidForm = true;
$(this.form).find(inputSelector).each(function() {
if (!this.value.trim()) {
isValidForm = false;
}
});
$(this.form).find('.monitored-btn').prop('disabled', !isValidForm);
return isValidForm;
}
$('.monitored-btn').closest('form')
// in a user hacked to remove "disabled" attribute, also monitor the submit event
.submit(function() {
// launch checkForm for the first encountered input,
// use its return value to prevent default if form is not valid
return checkForm.apply($(this).find(':input')[0]);
})
.find(inputSelector).keyup(checkForm).keyup();
</script>
I would do this very similarly to Kubwimana Adrien's answer with initially rendering a disabled button.
Also, generally, it is not considered secure to set initial state of validation booleans to TRUE. Thus, changing the code a little.
const inputSelector = ':input[required]:visible';
function checkForm() {
// here, "this" is an input element
var isValidForm = false;
$(this.form).find(inputSelector).each(function() {
if (((this.type != 'checkbox') && (this.value.trim() != "")) || (this.type == 'checkbox' && this.checked)) {
isValidForm = true;
}
else{
isValidForm = false
return false //break out of each loop
}
});
$(this.form).find('.monitored-btn').prop('disabled', !isValidForm);
return isValidForm;
}
$('.monitored-btn').closest('form')
// in a user hacked to remove "disabled" attribute, also monitor the submit event
.submit(function() {
// launch checkForm for the first encountered input,
// use its return value to prevent default if form is not valid
return checkForm.apply($(this).find(':input')[0]);
})
.find(inputSelector).on("keyup change", checkForm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form action="#otherForm">
Name * <input name="otherForm-name1" placeholder="required" required> <br />
Tel * <input name="otherForm-surname" placeholder="required" required> <br />
<input type="checkbox" name="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
<button id="otherForm-submitBtn" class="monitored-btn" type="submit" disabled>Submit</button>
</form></body>
CSS only required
#otherForm-submitBtn {
enabled: false;
color: grey;
}
input[type='checkbox']:checked ~ #otherForm-submitBtn {
enabled: true;
color: black;
}
<form action="#otherForm">
Name * <input name="otherForm-name1" placeholder="required" required> <br />
Tel * <input name="otherForm-surname" placeholder="required" required> <br />
<input type="checkbox" name="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
<button id="otherForm-submitBtn" class="monitored-btn" type="submit">Submit</button>
</form>
Keyup event won't work on a checkbox also it's better to check for checked prop instead of value on a checkbox. Try this:
const inputSelector = ':input[required]:visible';
function checkForm() {
// here, "this" is an input element
var isValidForm = true;
$(this.form).find(inputSelector).each(function() {
if (!this.value.trim() || (this.type == 'checkbox' && !this.checked)) {
isValidForm = false;
}
});
$(this.form).find('.monitored-btn').prop('disabled', !isValidForm);
return isValidForm;
}
$('.monitored-btn').closest('form')
// in a user hacked to remove "disabled" attribute, also monitor the submit event
.submit(function() {
// launch checkForm for the first encountered input,
// use its return value to prevent default if form is not valid
return checkForm.apply($(this).find(':input')[0]);
})
.find(inputSelector).on("keyup change", checkForm);
You need to check that condition in everytime user type or click checkbox , and toggle disable by removeAttr and attr ..
$("form input").keyup(check);
$("form input:checkbox").on("click", check);
function check() {
if($("input[name='otherForm-name1']").val() != "" &&
$("input[name='otherForm-surname']").val() != "" &&
$("input[name='otherForm-chcekbox']").prop("checked") == true) {
$("#otherForm-submitBtn").removeAttr("disabled");
return;
}
$("#otherForm-submitBtn").attr("disabled",true);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#otherForm">
Name * <input name="otherForm-name1" placeholder="required" required> <br />
Tel * <input name="otherForm-surname" placeholder="required" required> <br />
<input type="checkbox" name="otherForm-chcekbox" id="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
<button id="otherForm-submitBtn" class="monitored-btn" type="submit" disabled>Submit</button>
</form>
Disable the button with disable attribute. Then listen for the checkbox change event, and either remove the attribute or add it.
<form action="#otherForm">
<input type="checkbox" name="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
<button id="otherForm-submitBtn" class="monitored-btn" type="submit" disabled>Submit</button>
</form>
$(".otherForm-chcekbox").change(function() {
if(this.checked) {
if (checkForm()) {
$("otherForm-submitBtn").removeAttr("disabled");
}
} else {
$("otherForm-submitBtn").attr("disabled", "disabled");
}
});

Uncheck a checkbox and another checkbox will untick

I have two checkboxes in a form. onclick if a checkbox called email is unchecked how can I get the other checkbox to also uncheck (if it is checked) ?
document.getElementById('email').onclick = function() {
if (!this.checked) {
!document.getElementById("other").checked;
} else {
// if not checked ...
}
};
Am I completey barking up the wrong tree? Any help appriciated
To synchronize the checking of the both at the same time you need just to use this.checked of the first clicked one on the checked attribute of the second one like :
document.getElementById("other").checked = this.checked;
NOTE : That will work on one way, what means the check will be synchronized just when you click on the first checkbox that you've attached the click event to.
document.getElementById('email').onclick = function() {
document.getElementById("other").checked = this.checked;
};
<input id="email" type="checkbox" /> CHECKBOX 1
<br>
<input id="other" type="checkbox" /> CHECKBOX 2
You can make it like :
<form id="test" action="#" method="post">
<div>
<input type="checkbox" name="check" id="check"/>
</div>
<div>
<input type="checkbox" name="check2" id="check2"/>
</div>
</form>
document.getElementById('check').onclick = function() {
if (!this.checked) {
document.getElementById("check2").checked = false;
} else {
// other logic ...
}};
Test it online on jsfiddle : https://jsfiddle.net/3dtq0w8x/
In your test code you are not setting the checked property of "other" to any value.
You are just reading its value, then inverting it (with !).
You could try:
document.getElementById("other").checked = false;
You can add event listener to email checkbox (which is a good practice) and then check if it is check or not and deal with the other checkbox according to that
For example
var ckb = document.getElementById('email')
ckb.addEventListener("click", function(e){
if(!e.target.checked)
document.getElementById('ot').checked = false;
})
<input type="checkbox" name="na" value="email" id="email">Email<br>
<input type="checkbox" name="na" value="other" id="ot">Other
This should help
function check() {
if(document.getElementById("email").checked){
document.getElementById("other").checked = true;
}else{
document.getElementById("other").checked = false;
}
}
HTML
<input type='checkbox' id='email' name='checkbox' onclick="check()" >email
<input type='checkbox' id='other' name='checkbox'>other

jQuery validation to ensure that at least one radiobutton value is true

I've a form that has two questions. The first question asks whether the product value is greater than a fixed certain amount and the second question asks if the product value is less than the fixed amount. When the user tries to submit the form, the form should be validated to confirm that at least one question has been answered as yes. If both questions are answered as no, the form valid property $("#form").valid() should be false and a div containing an error message should be displayed on the page. How can I achieve this using jQuery validation?
A simplified version of the form looks something like
<form id="billing" method="POST">
<div>
<label for "billAmountLess">Value is less than 1000</label>
<input id="billAmountLessY" name="billAmountLess" type="radio" required value="True">
<label for "billAmountLessY">Yes</label>
<input id="billAmountLessN" name="billAmountLess" type="radio" required value="False">
<label for "billAmountLessN">No</label>
</div>
<div>
<label for "billAmountMore">Value exceeds 1000</label>
<input id="billAmountMoreY" name="billAmountMore" type="radio" required value="True">
<label for "billAmountMoreY">Yes</label>
<input id="billAmountMoreN" name="billAmountMore" type="radio" required value="False">
<label for "billAmountMoreN">No</label>
</div>
<div id="errorDiv" style="display:none">Error!!!!
</div>
<div>
<input type="submit" value="Submit">
</div>
</form>
The jQuery validation that I'm trying is
$('#billing').validate({
rules: {
billAmountMore: {
equalTo: {
param: '#billAmountMoreY',
depends: function(element) {
$("errorDiv").show();
return $("#input[name='billAmountLess']:checked").val() == "false";
}
}
}
}
});
I've created a jsfiddle for this.
You can use this code
function validate(){
console.log($("input[name='billAmountLess']:checked").val());
console.log($("input[name='billAmountMore']:checked").val());
}
to retrieve the radio button value.
In your code this line:
return $("#input[name='billAmountLess']:checked").val() == "false";
should remove the "#" before 'input' as it's indicating the 'id' of an element. Maybe that's why it's not working.
Simple you can do this in custom validation function. Update your form tag -
<form id="billing" onsubmit="return validate();" method="POST">
Then -
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
function validate(){
var billLess = $("input[name='billAmountLess']:checked").val();
var billMore = $("input[name='billAmountMore']:checked").val();
if(billLess == "False" && billMore == "False"){
$("#errorDiv").show();
return false;
}
else{
return true;
}
}
</script>

How do I show an input field if a radio button is checked using jquery

I have a radio button called "other," and when checked, I want a input field called "other-text" to show up. It's fairly simple, but I've been failing all morning.
<input name="ocalls" type="radio" name="other" id="other-radio" value="Yes"><b>Other</b><br />
<input type="text" name="other-text" id="other-text" style="display:none" />
Here is my javascript:
jQuery(function(){
jQuery("input[name=other]").change(function(){
if ($(this).val() == "Yes") {
jQuery("#other-text").show()
}
else {
jQuery("#other-text").hide();
}
});
});
JSFiddle of the failure. http://jsfiddle.net/Wpt3Y/532/
This works
jQuery("#other-radio").change(function(){...
Just updated your jsfiddle: http://jsfiddle.net/Wpt3Y/539/
<pre><input type="radio" name="other" id="other-radio" value="Yes"><b>Other</b></pre>
Your code works, you simply mistyped your radio input, it had two name attributes.
I suggest to go this way. Tried to use prop() but realised you use old version of jquery
jQuery("input:radio[name='ocalls']").change(function(){
if ($(this).attr("checked") == true) {
jQuery("#other-text").show();
}
else {
jQuery("#other-text").hide();
}
});
example with radio
Instead you can use checkbox:
html
<input name="ocalls" type="checkbox" name="other" id="other-radio" value="Yes"><b>Other</b><br />
<input type="text" name="other-text" id="other-text" style="display:none" />
js
jQuery("input:checkbox[name='ocalls']").change(function(){
if ($(this).attr("checked") == true) {
jQuery("#other-text").show();
}
else {
jQuery("#other-text").hide();
}
});
example with checkbox
<form>
<input name="ocalls" type="radio" name="other" id="other-radio" value="Yes">
<b>Other</b><br />
</input>
<input type="text" name="other-text" id="other-text" style="display: none;" />
</form>
jQuery(function(){
jQuery("#other-radio").change(function(){
if ($(this).val() == "Yes") {
jQuery("#other-text").show()
}
else {
jQuery("#other-text").hide();
}
});
});
Try this.
If you want that toggle effect you can use this code with the checkbox.
jQuery(function(){
jQuery("input[name=ocalls]").change(function(){
if($(this).attr("checked"))
{
$("#other-text").show();
}
else
{
$("#other-text").hide();
}
});
});
Your code is not working because you have name attribute twice in radio button.
use this:
<input type="radio" name="other" id="other-radio" value="Yes">
remove name="ocalls" attribute.

Can I use jQuery to check whether at least one checkbox is checked?

I have the following HTML form which can have many checkboxes. When the submit button is clicked, I want the user to get a javascript alert to check at least one checkbox if none are checked. Is there an easy way to do this using jQuery?
<form name = "frmTest" id="frmTest">
<input type="checkbox" value="true" checked="true" name="chk[120]">
<input type="checkbox" value="true" checked="true" name="chk[128]">
<input type="checkbox" name="chk[130]">
<input type="checkbox" name="chk[143]">
<input type="submit" name="btnsubmit" value="Submit">
</form>
if(jQuery('#frmTest input[type=checkbox]:checked').length) { … }
$('#frmTest input:checked').length > 0
$("#frmTest").submit(function(){
var checked = $("#frmText input:checked").length > 0;
if (!checked){
alert("Please check at least one checkbox");
return false;
}
});
$("#show").click(function() {
var count_checked = $("[name='chk[]']:checked").length; // count the checked rows
if(count_checked == 0)
{
alert("Please select any record to delete.");
return false;
}
if(count_checked == 1) {
alert("Record Selected:"+count_checked);
} else {
alert("Record Selected:"+count_checked);
}
});
$('#fm_submit').submit(function(e){
e.preventDefault();
var ck_box = $('input[type="checkbox"]:checked').length;
// return in firefox or chrome console
// the number of checkbox checked
console.log(ck_box);
if(ck_box > 0){
alert(ck_box);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name = "frmTest[]" id="fm_submit">
<input type="checkbox" value="true" checked="true" >
<input type="checkbox" value="true" checked="true" >
<input type="checkbox" >
<input type="checkbox" >
<input type="submit" id="fm_submit" name="fm_submit" value="Submit">
</form>
<div class="container"></div>
$('#frmTest').submit(function(){
if(!$('#frmTest input[type="checkbox"]').is(':checked')){
alert("Please check at least one.");
return false;
}
});
is(':checked') will return true if at least one or more of the checkboxes are checked.

Categories

Resources