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

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>

Related

How can I have the user click two Terms and Conditions before allowing them to proceed?

I'm trying to make it so that a user has to accept two terms and conditions before being able to click the "Agree and Continue" button. I tried to insert a second checkbox but then the user can just click the "Agree and Continue" button without either box being checked, so this code only has one checkbox.
Thanks!
<SCRIPT language=JavaScript>
<!--
function checkCheckBox(f){
if (f.agree.checked == false )
{
alert('Please check the box to continue.');
return false;
}else
return true;
}
//-->
</SCRIPT>
<form action="https://google.com" method="GET" onsubmit="return checkCheckBox(this)">
<!--Enter your form contents here-->
<input type="checkbox" value="0" name="agree">
<b> I Agree to the Terms and Conditions and Privacy Policy</b>
<br><br>
<b> I understand that I am accessing a third-party site and will abide by their Terms and Conditions and Privacy Policy</b><br>
<br>
<input type="submit" value="Agree and Continue">
</form>
You can make the checkbox required with:
<form>
<input type="email" required />
<input type="password" required>
<input type="checkbox" required><label for="scales">I'm agree</label>
<input type="submit">
</form>
It will generate:
You don't need any other javascript check, just the 'required' attributes.
Add a second checkbox with an explicit name and then use the boolean "or", ||, to see if both are not checked. The else isn't needed because the first condition returns so it is safe to remove.
function checkCheckBox(f) {
if (!f.agree.checked || !f.agree_third_party.checked) {
alert('Please check the box to continue.');
return false;
}
return true;
}
And alternative is to break it up so that you can give different messages:
function checkCheckBox(f) {
if (!f.agree.checked) {
alert('Please check the first box to continue.');
return false;
}
if (!f.agree_third_party.checked) {
alert('Please check the second box to continue.');
return false;
}
return true;
}
Further, you can completely remove JavaScript and use the native HTML5 required attribute. (I couldn't help wrapping the checkboxes in labels for convenience and accessibility, but they aren't required.)
<label for="agree">
<input type="checkbox" value="0" name="agree" id="agree" required>
<b> I Agree to the Terms and Conditions and Privacy Policy</b>
</label>
<br><br>
<label for="agree_third_party">
<input type="checkbox" value="0" name="agree_third_party" id="agree_third_party" required>
<b> I understand that I am accessing a third-party site and will abide by their Terms and Conditions and Privacy Policy</b><br>
</label>
And if you want to customize the message:
<input type="checkbox" value="0" name="agree" id="agree" required
oninvalid="this.setCustomValidity('You must agree to our terms and conditions.')"
oninput="this.setCustomValidity('')"
>

Require all boxes on form be checked

I am trying to get a form to require that all checkboxes be checked to indicate the person has read all of the sections before allowing submission. The html is like
function checkform()
{
if (!this.rsa.secOne.checked)
{
alert('All boxes must be checked');
return false;
}
else if (!this.rsa.secTwo.checked)
{
alert('All boxes must be checked');
return false;
}
else if (!this.rsa.secThree.checked)
{
alert('All boxes must be checked');
return false;
}
return true;
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<link href="style.css" rel="stylesheet">
<meta charset="utf-8">
<title>Exhibit C</title>
</head>
<body>
<form action="rsaOne.php" method="post" onsubmit="return checkForm(this);" id="rsa" name="rsa">
<input type="checkbox" id="secOne" name="secOne"><b>SECTION 1. </b><u>
I get checkform is not defined. How can I change this to make it work? There are 23 checkboxes total, I can copy the else if over and over and change the identifier, if someone can just tell me what to change to make this much work.
Using required:
Just add a required attribute to each input element like this:
<input type="checkbox" id="secOne" name="secOne" required>
<input type="checkbox" id="secTwo" name="secTwo" required>
Using HTMLFormElement.elements to dynamically set required attribute with JavaScript:
If there are too many checkboses and/or you want to dynamically use JavaScript to add the required attribute to all your checkboxes, you can just use the HTMLFormElement.elements property to get all the form controls (here, your checkboxes) inside your form and then use the Array.from() method to get a shallow-copied array of the HTMLFormControlsCollection which you can now loop over and use the setAttribute() method to dynamically set a required attribute to all the checkboxes.
Check and run the following Code Snippet or open this JSFiddle link for a practical example of the above approach:
// get the form
const form = document.getElementById("rsa");
// get the form controls
let x = form.elements;
// Convert the list of form controls to an array and set the required attribute to each control
Array.from(x).forEach(e => {
e.setAttribute("required", "");
})
<form action="rsaOne.php" method="post" onsubmit="return checkForm(this);" id="rsa" name="rsa">
<input type="checkbox" id="secOne" name="secOne" required>
<input type="checkbox" id="secTwo" name="secTwo" required>
<input type="checkbox" id="secThree" name="secThree" required>
<input type="checkbox" id="secFour" name="secFour" required>
<button type="submit">SUBMIT</button>
</form>
This will work:
function checkForm() {
return [...document.querySelectorAll(".reqCheck")].every(el => el.checked)
}
Formatted for testing purposes:
function checkForm() {
const allChecked = [...document.querySelectorAll(".reqCheck")].every(el => el.checked)
console.log(allChecked)
return allChecked
}
<form action="rsaOne.php" onsubmit="return checkForm()" id="rsa" name="rsa">
<input type="checkbox" class="reqCheck" name="secOne" id="secOne">
<label for="secOne"> SECTION 1.</label><br />
<input type="checkbox" class="reqCheck" name="secTwo" id="secTwo">
<label for="secTwo">SECTION 2.</label><br />
<input type="checkbox" class="reqCheck" name="secThree" id="secThree">
<label for="secThree"> SECTION 3.</label><br />
<input type="submit" value="Submit" />
</form>
You got the error because you put checkForm() with a capital F on the onSubmit callback but when you created the function it is checkform().
Just change checkForm() to checkform()

How to use Javascript/JQuery to verify that at least two fields in a checkbox are selected?

I am trying to create Javascript verification code for a form, so that each section of the form is verified after hitting "submit". I am having trouble writing the code so that the checkbox section of the form verifies that two or more boxes have been selected. I tried to start simple by writing the code so that a div, errorcheckbox, would display a message if no checkbox is selected at all. However it does not work. Here is the HTML and script for the code pertaining to the checkbox:
HTML:
<form action="#" method="POST">
<div class="contactForm">
<label for="checkbox" id="checkbox" name="checkbox">Contactee Type: </label><br>
<div id="errorcheckbox" class="error"></div>
<input type="checkbox" name="type1" value="Individual">Individual<br>
<input type="checkbox" name="type2" value="Catering">Business:Catering<br>
<input type="checkbox" name="type3" value="Partner">Business:Partner<br>
</div>
<div class="button"><input type="button" name="submit" id="submit" value="Submit"></div>
</form>
and the Javascript:
$("document").ready(function(){
console.log("Loaded");
$("#submit").click(function(){
checkContactee();
});
$("#checkbox").change(function(){
console.log("Something in contactee changed");
checkContactee();
});
function checkContactee(){
if (document.getElementById("checkbox").checked == false){
$("#errorcheckbox").html("<p>You missed this field</p>");
$("#errorcheckbox").addClass("showerror");
}
else{
$("#errorregarding").html("");
$("#errorregarding").removeClass("showerror");
}
}
Right now, the code does nothing. The errorcheckbox div doesn't appear, and there is no change in the console log if a checkbox item is selected. So, this is one problem I'm having. I still need to verify that two or more of the boxes are checked. I'm hoping to do this by adding an if else statement to the checkContactee function, but am not sure how.
Looking at your code I would recommend a couple of things. Your check boxes look like you want to capture multiple values for a contact type, so they should have the same name attribute. Each check box should have it's own label and where you have a label now you should use a fieldset and legend.
By wrapping the checkboxes in a fieldset we can then use that as part of the validation process.
$("document").ready(function() {
console.log("Loaded");
$("fieldset[data-mincheckboxchecked] [type=checkbox]").on("click", function() {
console.log("Click")
//Get the parent fieldset
let $parent = $(this).closest("fieldset[data-mincheckboxchecked]");
validateMultiCheckBox($parent);
});
});
function validateMultiCheckBox($parent) {
console.log($parent)
//Get minimum checked from the data attribute
let minCheked = $parent.data("mincheckboxchecked");
minChecked = parseInt(minCheked, 10);
//Get the number of checked checkboxes in the parent
let numCheked = $parent.find("[type=checkbox]:checked").length;
//Validation Logic
if (numCheked < minCheked) {
$parent.find(".error").html("<p>Please select at least " + minChecked + " option" + (minCheked !== 1 ? "s" : "") + "</p>");
$parent.find(".error").addClass("showerror");
return false;
} else {
$parent.find(".error").html("");
$parent.find(".error").removeClass("showerror");
return true;
}
}
$("#submit").click(function() {
var isValid = false;
var multiCheckValid = true;
//Validate each group of multi checkboxes
$("fieldset[data-mincheckboxchecked]").each(function() {
console.log(this);
if (!validateMultiCheckBox($(this))) {
multiCheckValid = false;
}
})
//Normally you'e set this to return false, leaving like
//this for demo purposes
console.log(multiCheckValid);
return isValid;
});
.error {
display: none;
color: red;
}
.error.showerror {
display: block;
}
fieldset label {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="POST">
<div class="contactForm">
<fieldset data-mincheckboxchecked="2">
<legend>Contactee Type: </legend>
<div id="errorcheckbox" class="error"></div>
<label><input type="checkbox" name="contactType" value="Individual">Individual</label>
<label><input type="checkbox" name="contactType" value="Catering">Business:Catering</label>
<label><input type="checkbox" name="contactType" value="Partner">Business:Partner</label>
</fieldset>
<fieldset data-mincheckboxchecked="1">
<legend>One Required: </legend>
<div id="errorcheckbox" class="error"></div>
<label><input type="checkbox" name="oneReq" value="1">A Thing</label>
<label><input type="checkbox" name="oneReq" value="2">Another Thing</label>
<label><input type="checkbox" name="oneReq" value="3">Yet another thing</label>
</fieldset>
<fieldset data-mincheckboxchecked="3">
<legend>Top 3 Movies: Three required</legend>
<div id="errorcheckbox" class="error"></div>
<label><input type="checkbox" name="movie" value="Top Gun">Top Gun</label>
<label><input type="checkbox" name="movie" value="Terminator">Terminator</label>
<label><input type="checkbox" name="movie" value="Sound Of Music">Sound OF Music</label>
<label><input type="checkbox" name="movie" value="Mission Impossible">Mission Impossible</label>
</fieldset>
</div>
<div class="button"><input type="button" name="submit" id="submit" value="Submit"></div>
</form>
This way it's extensible and not reliant on Ids.
You can use the :checked which the selector to get the checked items.
function validate() {
console.log('Total Checked = ' + $('.contactForm input[type="checkbox"]:checked').length);
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<div class="contactForm">
<label for="checkbox" id="checkbox" name="checkbox">Contactee Type: </label><br>
<div id="errorcheckbox" class="error"></div>
<input type="checkbox" name="type1" value="Individual">Individual<br>
<input type="checkbox" name="type2" value="Catering">Business:Catering<br>
<input type="checkbox" name="type3" value="Partner">Business:Partner<br>
<button onclick="validate()">Validate</button>
</div>
use a class for your checkboxes and select that or use tag name and type to select tags,
you are using the id of a label tag for checking checkboxes
, use .is() method in jquery to check is checked
$("document").ready(function(){
console.log("Loaded");
$("#submit").click(function(){
checkContactee();
});
$("input[type='checkbox']").change(function(){
console.log("Something in contactee changed");
checkContactee();
});
function checkContactee(){
if ($("input[type='checkbox']").is(':checked'){
$("#errorcheckbox").html("<p>You missed this field</p>");
$("#errorcheckbox").addClass("showerror");
}
else{
$("#errorregarding").html("");
$("#errorregarding").removeClass("showerror");
}
}
var checkedCount=$("input[name^='type']:checked).length - this pulls all inputs, looks for those with the name beginning with "type", keep the ones that are checked, and returns how many are check (here, assigned to the checkedCount variable). I'll leave further validation/scolding of the user up to you

regarding input name in javascript

Using jQuery mobile and javascript I'm attempting to produce a small quiz which would be functional on a smart phone. It isn't fully finished.
I'm attempting to create a list of radio buttons which one selected the value is carried over and submitted but why is the input name "radio=choice-v-6" when this is one of the options.
<script type="text/javascript">
var answer1 = 2;
function submit()
{
if ($('input[name=radio-choice-v-6]:checked', '#myForm').val() == answer1)
{
alert("Correct");
window.location = "#question-2"
}
else
{
alert("Incorrect");
window.location = "#incorrect"
}
}
</script>
then when I use the jQuery mobile pre-set button names I use.
<form id="myForm" name="myForm">
<fieldset data-role="controlgroup" id="radiobuttons" data-mini="true">
<input name="radio-choice-v-6" id="radio-choice-v-6a" type="radio" onclick="question1()" value="1">
<label for="radio-choice-v-6a">One</label>
<input name="radio-choice-v-6" id="radio-choice-v-6b" type="radio" onclick="question1()" value="2">
<label for="radio-choice-v-6b">Two</label>
<input name="radio-choice-v-6" id="radio-choice-v-6c" type="radio" onclick="question1()" value="3">
<label for="radio-choice-v-6c">Three</label>
</fieldset>
<td><button type="submit" id="submit" name="submit" value="Submit" onclick="submit()"></td>
</form>
I assumed I would put the input name as "radiobuttons" or "myForm"
I'm new to JavaScript and would like to know why "radio-choice-v-6" works.
'input[name=radio-choice-v-6]:checked' is the selector and targets only the radio button that is checked and has the name of radio-choice-v-6. The form in general cannot be deemed as checked and neither can the fieldset. So myForm and radiobuttons will not target the currently checked radio button.

jQuery, submit() with multiple forms using .each()

First off, I realize this is not an optimal solution, but the actual production environment is a product of a drunken orgy involving Magento and a lot of cheap plugins, so don't judge me too harshly. I can't be held responsible for other peoples' messes.
I'm trying to submit multiple forms from one page using jQuery. It works fine in IE and FF. Page has four forms, which I loop through them in JS to see if their checkbox is checked and then submit them one by one, using .each() and .submit(). In Chrome, jQuery(this).submit() does not fire until after you have completely exited the function, and then it only actually submits the last form.
Uses jQuery 1.8.1. The working mockup is here
The code follows:
<!DOCTYPE html>
<html>
<head>
<title>asdfad</title>
<script type="text/javascript" src=http://code.jquery.com/jquery-1.8.1.min.js"></script>
</head>
<body class=" listraknewsletter-index-index">
<form id="form4" method="post" class="signup-form"
action="http://www.example.com/action1"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue1"/>
<label for="checkbox">newsletter 1</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox"
name="sos-checkbox" />
</form>
<form id="form2" method="post" class="signup-form"
action="http://www.example.com/action2"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue2"/>
<label for="checkbox">newsletter 2</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox"
name="sos-checkbox" />
</form>
<form id="form3" method="post" class="signup-form"
action="http://www.example.com/action3"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue3"/>
<label for="checkbox">newsletter 3</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox" name="sos-checkbox" />
</form>
<form id="form1" method="post" class="signup-form"
action="http://www.example.com/action4"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue4"/>
<label for="checkbox">newsletter 4</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox" name="sos-checkbox" />
</form>
<!-- Area for entering in information -->
<form method="post" action="/">
<label for="email">email</label>
<input type="text" id = "nl_email" name="email"
size="40" maxlength="100" value = ""/>
<label for="name">name</label>
<input type="text" name="name" id = "nl_name" maxlength="50" size="40" value=""/>
<input type="button" value="Subscribe" onclick="processSignups();" />
<script type="text/javascript">
// requires jQuery
jQuery.noConflict();
function processSignups() {
// make sure you have a valid email and name
// make sure email is at least not null
// this is not a pretty regex for sure lol,
// but tis' RFC 2822 valid
var nl_email = jQuery('input#nl_email').val();
var re = new RegExp(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/);
if (re.test(nl_email) == false) {
alert('Please enter a valid email');
return false;
}
// name is not null
if (jQuery('input#nl_name').val() == '') {
alert('Please enter your name');
return false;
}
// make sure at least one checkbox is selected
var checkboxes = jQuery('input.signup-checkbox');
var atLeastOne = false;
jQuery(checkboxes).each(function() {
if (jQuery(this).is(':checked')) {
atLeastOne = true;
}
});
if (atLeastOne == false) {
alert('Please select at least one newsletter checkbox');
return false;
}
// select your forms by class
// var forms = jQuery('form.signup-form');
// for each form
var formIds = new Array();
jQuery('form.signup-form').each(function(index) {
// get the checkbox
var checkbox;
checkbox = jQuery(this).children('input.signup-checkbox');
// if it is checked
if (jQuery(checkbox).is(':checked')) {
// add a hidden field to the form to hold the email
jQuery(this).append('<input type="hidden" name="email" value="' + nl_email + '" />');
// and submit form
jQuery(this).submit();
}
});
// might as well clear the email and name inputs
jQuery('input#nl_name').val('');
jQuery('input#nl_email').val('');
// return false;
}
</script>
</form>
</body>
</html>
Chrome doesn't treat target="_blank" like the other browsers. Try _tab, or dynamically changing them $(this).attr('target', '_'+$(this).attr('id'));

Categories

Resources