Fancy sliding form with more validation - javascript

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.

Related

Add number before input box text after validation using JavaScript

I have this HTML form
more on top ...
<div class="form-group row">
<label for="phone" class="col-sm-3 col-form-label">Phone</label>
<div class="col-sm-9">
<input type="text" name="phone" id="phone" class="form-control" >
</div>
</div>
more on bottom ...
Here I am putting the number e.g 1671133639 and if its validate then I am adding 880 before this number. But it's adding before the input field, not input text. I mean final result should be: 8801671133639
JS Code I am using:
if (phone.value == "") {
alert("Phone number is required");
phone.focus();
return false;
} else if (!phoneRegex.test(phone.value)) {
alert("Phone number must contain only numerical value.");
phone.focus();
return false;
} else if ( phone.length > 13 ) {
alert("Invalid phone number is given.");
phone.focus();
return false;
} else {
var text = document.createTextNode('+88');
var child = document.getElementById('phone');
child.parentNode.insertBefore(text, child);
}
Don't use insertBefore, assign the new string to the input's value attribute.
const text = '+88';
const child = document.getElementById('phone');
const value = child.value;
phone.value = text + value;
document.querySelector('button').addEventListener('click', function() {
const text = "+88";
const phoneInput = document.getElementById('phone');
const value = phoneInput.value;
phoneInput.value = text + value;
})
<input type="text" value="1671133639" type="string" id="phone">
<button>Append Phone Code</button>

javascript - Merging checkboxes into one field in form

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;
}

How can I check if the input is empty in JavaScript? [duplicate]

This question already has answers here:
How do I check for an empty/undefined/null string in JavaScript?
(52 answers)
Closed 7 years ago.
I am trying to make a factorial calculator. How can I check if the input is empty or not? I tried 'null'. But it didn't work or I couldn't use it properly.
sorry for the stupid question. I am newbie in JavaScript
function myFriday() {
var input = document.getElementById("input1").value;
var ever = function () {
if( !(isNaN(input))) {
var result = 1;
for(var i = 1; i <= input; i++ ) {
result = result * i
}
return result;
}
else if (input == null){
return "Please input a number"
}
else{
return "Please input a number"
}
}
document.getElementById("input2").value = ever();
}
<p>Input: <input type="text" id = "input1" /></p>
<p>Input: <input type="text" id = "input2" /></p>
<button onclick = "myFriday()">Calculate</button>
<p >RESULT: <span id = "result" style = "color:red"></span> </p>
function myFriday() {
var input = document.getElementById("input1").value;
var ever = function() {
if (input.trim() == '') {
return "Please input a number"
} else if (!(isNaN(input))) {
var result = 1;
for (var i = 1; i <= input; i++) {
result = result * i
}
return result;
}
}
document.getElementById("input2").value = ever();
}
<p>Input:
<input type="text" id="input1" />
</p>
<p>Input:
<input type="text" id="input2" />
</p>
<button onclick="myFriday()">Calculate</button>
<p>RESULT: <span id="result" style="color:red"></span>
</p>
is that what you looking for?
function myFriday() {
var input = document.getElementById("input1").value;
var ever = function () {
if(input.match(/\D/) == null){ // changes made here
var result = 1;
for(var i = 1; i <= input; i++ ) {
result = result * i
}
return result;
}
else{ // one else is enough
return "Please input a number"
}
}
document.getElementById("input2").value = ever();
}
<p>Input: <input type="text" id = "input1" /></p>
<p>Input: <input type="text" id = "input2" /></p>
<button onclick = "myFriday()">Calculate</button>
<p >RESULT: <span id = "result" style = "color:red"></span> </p>
When you use .value you get a string value in return.
This means that when you enter nothing in the input it'll return ""
So you should change this piece of code
input == null
Into this
input === ""
Note that I also wrote === instead of ==
Using === in javascript is faster than == when the objects are of the same type.

Loop Over Input Fields; Stop After Two Iterations

I have five form fields that will initially NOT be pre-populated with any values.
If a user fills out one of the fields, the next time they visit the form that field will be pre-populated with the value from the previous visit.
Here's what I'm trying: I'd like to create a loop that iterates through the fields. It will always check to see if there are empty fields. After finding 2 empty fields, the loop will stop and only show those 2 empty fields, while the other fields are hidden.
Here's what I have so far...I just can't figure how to stop after iterating through two fields,
HTML:
<form action="">
<input id="first" type="text" value="" />
<input id="second" type="text" value="" />
<input id="third" type="text" value="" />
<input id="fourth" type="text" value="" />
<input id="fifth" type="text" value="" />
</form>
JS:
$(document).ready(function() {
$('input').hide();
var firstValue = $('input[id="first"]').val(),
secondValue = $('input[id="second"]').val(),
thirdValue = $('input[id="third"]').val(),
fourthValue = $('input[id="fourth"]').val(),
fifthValue = $('input[id="fifth"]').val();
var firstField = $('input[id="first"]'),
secondField = $('input[id="second"]'),
thirdField = $('input[id="third"]'),
fourthField = $('input[id="fourth"]'),
fifthField = $('input[id="fifth"]');
var formValues = [firstValue, secondValue, thirdValue, fourthValue, fifthValue];
var fieldIds = [firstField, secondField, thirdField, fourthField, fifthField];
for (var i = 0; i < fieldIds.length; i++) {
for (var i = 0; i < formValues.length; i++) {
if ( formValues[i] === '' ) {
fieldIds[i].show();
return false;
}
}
}
});
Take all input fields, take the first two empty fields and show them; finally, take the complement of that to hide the rest:
var $inputFields = $('form input:text'),
$emptyFields = $inputFields
.filter(function() { return this.value == ''; })
.slice(0, 2)
.show();
$inputFields
.not($emptyFields)
.hide();
Demo
$(document).ready(function() {
$('input').hide().each( function(){
var index=0; //initilialize the counter
if( $(this).val().length ){ //check for input's length
if(index < 2) {
$(this).show();
index=index+1 //or index++ if you like
}
else {
break;
}
}
}
)};
If you want to include select and textarea fields in your eligible input population, use $(':input').hide().each(...). If you have multiple forms on your page, you would want to include that in your selector, too: $('#intended_form').find(':input').hide().each(...).
http://api.jquery.com/each/
I think that Jack provides the best answer, but this should work too. here, i use a second counter j and break the loop when j % 2 == 0, so at this time its found two empty fields. this is known as a modulus or the modulo operator.
$(document).ready(function() {
$('input').hide();
var firstValue = $('input[id="first"]').val(),
secondValue = $('input[id="second"]').val(),
thirdValue = $('input[id="third"]').val(),
fourthValue = $('input[id="fourth"]').val(),
fifthValue = $('input[id="fifth"]').val();
var firstField = $('input[id="first"]'),
secondField = $('input[id="second"]'),
thirdField = $('input[id="third"]'),
fourthField = $('input[id="fourth"]'),
fifthField = $('input[id="fifth"]');
var formValues = [firstValue, secondValue, thirdValue, fourthValue, fifthValue];
var fieldIds = [firstField, secondField, thirdField, fourthField, fifthField];
var j = 0;
for (var i = 1; i < fieldIds.length; i++) {
if ( formValues[i] === '' ) {
fieldIds[i].show();
j++;//we found an empty field
if (j % 2 == 0)
{
break;
}
}
}
});

change form action value based on hidden field values

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

Categories