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()
Related
I have this html:
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<script src="js/filename.js"></script>
</head>
<body>
<form id = "dp5" action="" method="POST" onsubmit="Write_Text()">
<h3>5- Do you know any browsers?</h3>
<input id = "No" type="radio" name="dp5N" value="false">
<label for = "No">No </label>
<input id = "yes" type="radio" name="dp5S" value="true">
<label for = "yes">Yes</label>
<label for = "text">6 - Which?</label>
<input id = "text" type="text" name="dp5text" value="">
</form>
<div id="next">
<input id="sub" type="submit" name="submit" value="Next">
</div>
</body>
</html>
And this javascript "filename":
function Write_Text() {
let x = document.forms["dp5"]["No"].value;
if (x === "false") {
document.getElementById("text").disabled=true;
document.getElementById("text").value="";
} else {
document.getElementById("text").disabled =false;
}
}
The text box should start disabled and only be able when the user choose "yes" option. The function isn't working at all.
Your submit button is outside the form. Put it inside the form and it will work.
<form id = "dp5" action="" method="POST" onsubmit="Write_Text(); return false">
<h3>5- Do you know any browsers?</h3>
<input id = "No" type="radio" name="dp5N" value="false">
<label for = "No">No </label>
<input id = "yes" type="radio" name="dp5S" value="true">
<label for = "yes">Yes</label>
<label for = "text">6 - Which?</label>
<input id = "text" type="text" name="dp5text" value="">
<div id="next">
<input id="sub" type="submit" name="submit" value="Next">
</div>
</form>
Once you fix the problem Sreekanth MK pointed out, you'll have a new problem:
Nothing is preventing the default action of the form submission, which is to send the form data to the action URL (in your case it will be the page's own URL) and replace the current page with whatever that URL returns.
You need to prevent the default action. The minimal way is:
<form id = "dp5" action="" method="POST" onsubmit="Write_Text(); return false">
or
<form id = "dp5" action="" method="POST" onsubmit="event.preventDefault(); Write_Text();">
...but I recommend using modern event handling instead by removing the onsubmit attribute and changing the JavaScript like this:
function Write_Text(event) {
event.preventDefault();
let x = document.forms["dp5"]["No"].value;
if (x === "false") {
document.getElementById("text").disabled=true;
document.getElementById("text").value="";
} else {
document.getElementById("text").disabled =false;
}
}
document.getElementById("dp5").addEventListener("submit", Write_Text);
Note that you need to move your script tag. Putting script in head is an anti-pattern. Scripts go at the end of the page, right before the closing </body> tag.
Side note: You're free to do anything you like in your own code, but FWIW, the overwhelming convention in JavaScript is that function names start with a lower case letter and use camelCase, other than constructors which used initially-capped CamelCase instead. So writeText rather than Write_Text.
First of all, the submit problem can be easily solved by moving the button in the form and preventing the default behavior.
Among the submit problem, I think your code could be significantly improved by also solving the following problem: you can select both of the radio inputs: wrap them into a field-set and use the same name for them; why? it's easier to get the selected answer and can be extended to multiple inputs.
Below you have a working example with what I said.
Cheers!
function Write_Text(event) {
event.preventDefault();
let x = document.querySelector('input[name="ans"]:checked').value
console.log(x);
if (x === "false") {
document.getElementById("text").disabled=true;
document.getElementById("text").value="";
} else {
document.getElementById("text").disabled =false;
}
}
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
</head>
<body>
<h3>5- Do you know any browsers?</h3>
<form id="dp5" action="" method="POST" onsubmit="return Write_Text(event)">
<fieldset>
<input id="No" type="radio" name="ans" value="false">
<label for="No">No </label>
<input id="yes" type="radio" name="ans" value="true">
<label for="yes">Yes</label>
</fieldset>
<label for="text">6 - Which?</label>
<input id="text" type="text" name="dp5text" disabled value="">
<div id="next">
<input id="sub" type="submit" name="submit" value="Next">
</div>
</form>
</body>
</html>
you need to use event object here to prevent Default because page get refreshed onSubmit and then submit form in your function Write_Text()
function Write_Text(event) {
//This will prevent Default Behaviour
event.preventDefault();
let x = document.forms["dp5"]["No"].value;
if (x === "false") {
document.getElementById("text").disabled=true;
document.getElementById("text").value="";
} else {
document.getElementById("text").disabled =false;
}
// then submit using JS
}
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>
I am attempting to write JavaScript that traverses multiple HTML forms, checks an input for a given value on edit, then enables/disables the submit button for that form based on the input value.
I have a very simple example script, which overrides the onclick function of checkboxes, to test the flow of my code.
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<script type="text/javascript">
forms = document.getElementsByTagName("form");
for(i=0; i<forms.length; i++)
{
inputs = forms.item(i).getElementsByTagName("input");
inputs.item(0).onclick = function()
{
if(this.checked)
inputs.item(1).removeAttribute("disabled");
else
inputs.item(1).setAttribute("disabled","disabled");
}
}
</script>
What I expect to happen: the checkboxes change the value of the submit button in the same form.
What actually happens: all the checkboxes change the value of the submit button in the last form.
The actual code will be somewhat smarter, but I want to understand the flow of JavaScript code before progressing onto something more complex.
Thanks in advance!
Try something like this:
document.body.onchange = function(e) {
// this delegates all the way to the body - if you have a more specific
// container, prefer using that instead.
e = e || window.event;
var t = e.srcElement || e.target;
if( t.nodeName == "INPUT" && t.type == "checkbox") {
// may want to add a className to the checkboxes for more specificity
t.parentNode.getElementsByTagName('input')[1].disabled = !t.checked;
}
};
The reason you are seeing the behaviour you're getting is because inputs' value is not fixed, you are repeatedly re-assigning it to the next form's elements, ultimately resulting in the last one.
Given a simple html form like this:
<form name="myForm" action="#sent" method="post" ng-app>
<input name="userPreference1" type="text" ng-model="shipment.userPreference" />
<input name="userPreference1" type="text" ng-model="shipment.userPreference" />
<input name="userPreference1" type="text" ng-model="shipment.userPreference" />
... submit input and all the other code...
</form>
I need your help to know how to check on validation time, if at least one of the inputs is empty. The desired validation is the following. The user must complete at least one a preference.
Using jQuery this:
if ( $("input").val() == "" ) {
Works ok, but would like to figure out how to do the same thing using angular.
Thanks so much in advance,
Guillermo
So the idea is to disable the submit button if all inputs are blank. You can do like this
<form name="myForm" action="#sent" method="post" ng-app>
<input name="userPreference1" type="text" ng-model="shipment.userPreference1" />
<input name="userPreference1" type="text" ng-model="shipment.userPreference2" />
<input name="userPreference1" type="text" ng-model="shipment.userPreference3" />
<button type="submit" ng-disabled="!(!!shipment.userPreference1 || !!shipment.userPreference2 || !!shipment.userPreference3)">Submit</button>
</form>
!!str is to force to convert str to a boolean value. And both !!null and !!"" are evaluated to be false.
Demo
You can set the "required" in the input elements and style / code how you want to handle with $valid of a form. Check out http://dailyjs.com/2013/06/06/angularjs-7/
My solution was the following:
$scope.requiredInputsGroup = function () {
var isRequired = true;
if (!$scope.shipment) {
return true;
}
angular.forEach(["userPreference1", "userPreference2", "userPreference3"], function (input) {
if ($scope.shipment[input]) {
isRequired = false;
return false;
}
});
return isRequired;
};
You apply that method to a data-ng-required in each of the inputs...
<form name="myForm" action="#sent" method="post" ng-app>
<input name="userPreference1" type="text" ng-model="shipment.userPreference1" ng-required="requiredInputsGroup()" />
<input name="userPreference2" type="text" ng-model="shipment.userPreference2" ng-required="requiredInputsGroup()" />
<input name="userPreference3" type="text" ng-model="shipment.userPreference3" ng-required="requiredInputsGroup()" />
<button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>
And the last bit I applied was to make the button disabled with a simple myForm.$invalid
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'));