When a user selects either 2 or 3 checkboxes, and submits the form, I am trying to change the value of the form action attribute based on the values from 2 or 3 hidden fields.
The hidden fields with a default value of 0 are given the value of 1 when a checkbox is checked.
However it does not work and I'm unsure where to go from here.
My Form:
<form id="f" name="f" method="post" onsubmit="return checkform()" action="scripts/false.php">
RSA:<input type="hidden" id="RSAsel" name="RSAsel" value="0" />
RSG:<input type="hidden" id="RSGsel" name="RSGsel" value="0" />
RSF:<input type="hidden" id="RSFsel" name="RSFsel" value="0" />
<input name="submit" type="button" class="bodytxt" id="button" onclick="javascript:doSubmit();" value="Enrol in these courses">
</form>
<script>
function doSubmit() {
var RSAsel = parseInt(document.getElementById("RSAsel").value);
var RSGsel = parseInt(document.getElementById("RSGsel").value);
var RSFsel = parseInt(document.getElementById("RSFsel").value);
var target1 = 'scripts/process-combined-3.php';
var target2 = 'scripts/process-combined-rsa-rsg.php';
var target3 = 'scripts/process-combined-rsa-rsf.php';
var target4 = 'scripts/process-combined-rsg-rsf.php';
var theForm=document.getElementById('f');
if (RSAsel === 1 && RSGsel === 1 && RSFsel === 1) {
theForm.action = target1;
theForm.submit();
return true;
}
else if (RSAsel === 1 && RSGsel === 1) {
theForm.action = target2;
theForm.submit();
return true;
}
else if (RSAsel === 1 && RSFsel === 1) {
theForm.action = target3;
theForm.submit();
return true;
}
else if (RSGsel === 1 && RSFsel === 1) {
theForm.action = target4;
theForm.submit();
return true;
}
}
</script>
you need to get value of hidden field before trying to use it, like:
function doSubmit() {
var RSAsel = document.getElementById("RSAsel").value;
var RSGsel = document.getElementById("RSGsel").value;
var RSFsel = document.getElementById("RSFsel").value;
//rest of your code
}
and there's no header( "Location: $errorurl" ); in javascript, you are confusing it with PHP
Related
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;
}
I've got a form with three inputs. I want to be able to fill out two of the fields and automaticly fill the third field.
So, it should work like this:
- I fill out the first and second, the third gets calculated
- I fill out the first and last, the second gets calculated
- I fill out the second and last, the first gets calculated
I came up with this code:
$(document).on('keyup change', '[data-calc]', function() {
var a = $('[data-calc=a]') ,
aV = a.val() ,
b = $('[data-calc=b]') ,
bV = b.val() ,
c = $('[data-calc=c]') ,
cV = c.val();
if(aV.length != 0 && bV.length != 0) {
cV = parseInt(aV) + parseInt(bV);
c.val(cV).prop('disabled',true);
}
else if(aV.length != 0 && cV.length != 0) {
bV = parseInt(cV) - parseInt(aV);
b.val(bV).prop('disabled',true);
}
else if(bV.length != 0 && cV.length != 0) {
aV = parseInt(cV) - parseInt(bV);
a.val(aV).prop('disabled',true);
}
else {
$('[data-calc]').prop('disabled',false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" data-calc="a" /><br />
+<br />
<input type="text" data-calc="b" /><br />
=<br />
<input type="text" data-calc="c" />
Now the works fine when I fill out the first and second field.
But if I fill out the first, and the third after that, the third field gets disabled.
Any ideas?
This is how it should be, you should check which element was edited
$(document).on('keyup change', '[data-calc]', function(event) {
var $this = $(event.target || event.srcElement),
calc = $this.data('calc'),
$newCalc,
$a,
$b,
$c,
aV,
bV,
cV;
if (!calc) {
return;
}
$a = $('input[data-calc=a]');
$b = $('input[data-calc=b]');
$c = $('input[data-calc=c]');
$('input[data-calc]').prop('disabled', false);
aV = Number($a.val());
bV = Number($b.val());
cV = Number($c.val());
if (calc === 'a') {
if (!!aV && !!bV) {
$newCalc = $c.val(aV + bV);
} else if (!!aV && !!cV) {
$newCalc = $b.val(cV - aV);
}
} else if (calc === 'b') {
if (!!aV && !!bV) {
$newCalc = $c.val(aV + bV);
} else if (!!bV && !!cV) {
$newCalc = $a.val(cV - bV);
}
} else if (calc === 'c') {
if (!!aV && !!cV) {
$newCalc = $b.val(cV - aV);
} else if (!!bV && !!cV) {
$newCalc = $a.val(cV - bV);
}
}
if ($newCalc) { $newCalc.prop('disabled', true); }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" data-calc="a" />
<br />+
<br />
<input type="text" data-calc="b" />
<br />=
<br />
<input type="text" data-calc="c" />
The problem lies in you double binding to both keyup & change events. Remove the change from your code and you're set to go :-)
When you type a value into the 3rd field, first the keyup event fired, and all was well, and when the focus moved out of the 3rd field it fired the change event- which in turn disabled it since the 1st & 2nd fields both had values.
$(document).on('blur', '[data-calc]', function() {
var a = $('[data-calc=a]') ,
aV = a.val() ,
b = $('[data-calc=b]') ,
bV = b.val() ,
c = $('[data-calc=c]') ,
cV = c.val();
if(aV.length != 0 && bV.length != 0) {
cV = parseInt(aV) + parseInt(bV);
c.val(cV).prop('disabled',true);
}
else if(aV.length != 0 && cV.length != 0) {
bV = parseInt(cV) - parseInt(aV);
b.val(bV).prop('disabled',true);
}
else if(bV.length != 0 && cV.length != 0) {
aV = parseInt(cV) - parseInt(bV);
a.val(aV).prop('disabled',true);
}
else {
$('[data-calc]').prop('disabled',false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" data-calc="a" /><br />
+<br />
<input type="text" data-calc="b" /><br />
=<br />
<input type="text" data-calc="c" />
I'm working on a web form with several textboxes and a submit button. When the submit button is clicked, I am supposed to verify that the required fields all have input and that the age field is only numeric. For example, the user can enter 56, but 56 years-old, shouldn't be accepted. If the user enters invalid input or leaves required fields blank, the border around the appropriate textboxes should turn red.
However, as my code is written now all the required fields turn red regardless of input. Any ideas how I can fix this and make the page follow the couple of rules I listed?
Most Recent Code
<html>
<head>
<title>Project 4</title>
<style type="text/css">
body {
background-color: black;
color: blue;
text-align: center;
border: 2px double blue;
}
</style>
</head>
<body>
<h1>Welcome to my Web Form!</h1>
<p>
Please fill out the following information.<br>
Please note that fields marked with an asterisk (*) are required.
</p>
<form name="myForm" id="myForm" onsubmit="return validateForm()">
*Last Name: <br>
<input type="text" id="lastname">
<br>
First Name: <br>
<input type="text" id="firstname">
<br>
*Hobbies (separate each hobby with a comma): <br>
<input type="text" id="hobbies">
<br>
Pets:
<div id="petsContainer">
<input type="text" id="pets">
<input type="button" id="addPet" value="Add Pet">
</div>
<br>
Children:
<div id="childContainer">
<input type="text" id="children">
<input type="button" id="addKid" value="Add Child">
</div>
<br>
*Address: <br>
<input type="text" id="address">
<br>
*Phone Number:<br>
<input type="text" id="phone">
<br>
*Age: <br>
<input type="text" id="age">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
var validatePhoneOnKeyUpAttached = false;
var validateLNameOnKeyUpAttached = false;
var validateHobbiesOnKeyUpAttached = false;
var validateAddressOnKeyUpAttached = false;
var validateAgeOnKeyUpAttached = false;
function validateForm() {
if(!validatePhoneOnKeyUpAttached) {
document.getElementById("phone").onkeyup = checkPhone;
validatePhoneOnKeyUpAttached = true;
}
else if(!validateLNameOnKeyUpAttached) {
document.getElementById("lastname").onkeyup = checkEmpty;
validateLNameOnKeyUpAttached = true;
}
else if(!validateHobbiesOnKeyUpAttached) {
document.getElementById("hobbies").onkeyup = checkEmpty;
validateHobbiesOnKeyUpAttached = true;
}
else if(!validateAddressOnKeyUpAttached) {
document.getElementById("address").onkeyup = checkEmpty;
validateAddressOnKeyUpAttached = true;
}
else if(!validateAgeOnKeyUpAttached) {
document.getElementById("age").onkeyup = checkEmpty;
document.getElementById("age").onkeyup = checkAge;
validateAgeOnKeyUpAttached = true;
}
return checkEmpty() && checkPhone() && checkAge();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").style.borderColor="transparent";
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
document.getElementById("phone").style.borderColor="red";
return false;
}
}
function checkEmpty() {
var lname = document.forms["myForm"]["lastname"].value;
var pNum = document.forms["myForm"]["phone"].value;
var hobs = document.forms["myForm"]["hobbies"].value;
var live = document.forms["myForm"]["address"].value;
var yr = document.forms["myForm"]["age"].value;
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("hobbies").style.borderColor = (hobs == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
document.getElementById("address").style.borderColor = (live == "") ? "red" : "transparent";
document.getElementById("age").style.borderColor = (yr == "") ? "red" : "transparent";
}
function checkAge() {
var age = document.getElementById("age").value;
if(isNan(age)) {
return false;
}
else {
document.getElementById("age").style.borderColor="red";
return true;
}
}
document.getElementById("addPet").onclick=function() {
var div = document.getElementById("petsContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "pats[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
document.getElementById("addKid").onclick=function() {
var div = document.getElementById("childContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "child[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
</script>
</body>
</html>
The problem I'm currently having is that when I click the submit button, all the fields turn red for a split second, but then go back to the regular color and the input is erased. Any thoughts on how to fix this?
By including all of the borderColor="red" statements in a single code block, you're applying that style to all your inputs, even if only one of them failed validation. You need to separate out each statement so that it only applies to the individual field(s) that failed validation:
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
...
Also, I'm using the ternary operator ? : to clean up the code as well. These statements would replace the if-else block you've written.
I am using the following javascript functions in order to validate my form variables. Hope these will helpful for you.
var W3CDOM = (document.getElementsByTagName && document.createElement);
window.onload = function () {
document.forms[0].onsubmit = function () {
return validate()
}
}
function validate() {
validForm = true;
firstError = null;
errorstring = '';
var x = document.forms[0].elements;
for (var i = 0;i < x.length;i++) {
if (!x[i].value) {
validForm = false;
writeError(x[i], 'This field is required');
}
}
// This can be used to validate input type Email values
/* if (x['email'].value.indexOf('#') == -1) {
validForm = false;
writeError(x['email'],'This is not a valid email address');
}
*/
if (!W3CDOM)
alert(errorstring);
if (firstError)
firstError.focus();
return validForm;
}
function writeError(obj, message) {
validForm = false;
//if (obj.hasError) return false;
if (W3CDOM) {
obj.className += ' error';
obj.onchange = removeError;
var sp = document.createElement('span');
sp.className = 'error';
sp.appendChild(document.createTextNode(message));
obj.parentNode.appendChild(sp);
obj.hasError = sp;
} else {
errorstring += obj.name + ': ' + message + '\n';
obj.hasError = true;
}
if (!firstError)
firstError = obj;
return false;
}
function removeError() {
this.className = this.className.substring(0, this.className.lastIndexOf(' '));
this.parentNode.removeChild(this.hasError);
this.hasError = null;
this.onchange = null;
}
You can call the validations right after the form submission as given below.
<form name="loginForm" action="do.login" method="POST" class="form" onsubmit="return validate();">
I am using this fancy sliding box and having some problem with validation.It has default validation for checking where a field is empty or not but i want to add some more validation like two specific fields are equal or not or the length of a specific field is within the desired length or not.I have edited the code but facing a problem that is when a previous navigation field has any error it is also adding error class for the next navigation though it was filled correctly.
Here is my code(Be noted i don't know jquery well) :
function validateStep(step) {
if(step == fieldsetCount) return;
var error = 1;
var hasError = false;
$('#formElem').children(':nthchild('+parseInt(step)+')')
.find(':input:not(button)')
.each(function() {
var $this = $(this);
var valueLength = jQuery.trim($this.val()).length;
//i don't know how to generate a specific field value using this keyword
var pas=$('#myPassword').val().length;
var pas1=$('#myPassword').val();
var pas2=$('#VerifyPassword').val();
var pin1=$('#mPin').val();
var pin2=$('#vVPin').val();
var pas_ok=1;
if(pas1 != pas2 || pin1 ! =pin2 || pas < 5 ) {
pas_ok=0;
}
if(valueLength == '' || pas_ok==0) {
hasError = true;
$this.css('background-color','#FFEDEF');
} else {
$this.css('background-color','#FFFFFF');
}
});
var $link = $('#navigation li:nth-child(' + parseInt(step) + ') a');
$link.parent().find('.error,.checked').remove();
var valclass = 'checked';
if(hasError) {
error = -1;
valclass = 'error';
}
$('<span class="'+valclass+'"></span>').insertAfter($link);
return error;
}
Here is my form:
<div id="steps">
<form id="formElem" name="formElem" action="" method="post" >
<fieldset class="step">
<legend>Account</legend>
<p>
<label for="password">Password</label>
<input type="password" name="myPassword" id="myPassword" value="<?=$myPassword;?>" AUTOCOMPLETE=OFF />
</p>
<p>
<label for="password"> Verify Password</label>
<input type="password" name="VerifyPassword" id="VerifyPassword" value="<?=$VerifyPassword;?>" />
</p>
<p>
<label for="password"> Your Personal Pin </label>
<input type="pin" name="mPin" id="mPin" value="<?=$mPin;?>" />
</p>
<p>
<label for="password"> Verify Personal Pin </label>
<input type="pin" name="vVPin" id="vVPin" value="<?=$vVPin;?>" />
</p>
</fieldset>
</form>
</div>
What you are doing is checking all input fields for every each cycle again completeley. .each() gives you one input at a time. What you want to do is differentiate them via the input's respective id and then run the checks. The following code checks the length of all 4 input fields and marks them red if their length is zero and in case of the two verify input fields it also checks whether they are the same as their original input fields. The code is untested but you should get the idea.
$('#formElem').children(':nthchild('+parseInt(step)+')')
.find(':input:not(button)')
.each(function() {
var $this = $(this);
var value = $this.val();
var valueLength = jQuery.trim(value).length;
var pas_ok = 1;
var id = $this.attr("id");
if (id === 'VerifyPassword') {
var password = $('#myPassword').val();
var vPassword = value;
if (password !== vPassword)
pas_ok = 0;
} else if (id === 'vVPin') {
var pin = $('#mPin').val()
var vPin = value;
if (pin !== vPin || pin.length < 5)
pas_ok = 0;
}
if(valueLength === 0 || pas_ok === 0) {
hasError = true;
$this.css('background-color','#FFEDEF');
} else {
$this.css('background-color','#FFFFFF');
}
});
On a side note: Always use === instead of == if you compare something in javascript.
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>