Validation. Checking and calling a function - javascript

I want to call a function only when the form is valid. Validation works correctly, but I can not correctly call the addUser () function. The test worked, but it's looped, the next time it's called, the test is done twice, the next 5 times. There can be several telephones.
// code
if (lastName.value.match(letters)) {
for(var i = 0; i < phones.length; i++){
if (!phones[i].value.match(digts)) {
//checking
if(phones[phones.length - 1].value != '') {
addUser();
};
error.innerHTML = 'Only digits';
frm.insertBefore(error, phones[i]);
break;
}
}
} else {
if(user.value == ''){
//code
}
errorMessage = "false";
}
if (errorMessage !== "") {
event.preventDefault();
}
}
----------
function addUser(){
$('#registration').submit(function(event) {
alert(12);
//code
event.preventDefault();
var data = 'phones=' + JSON.stringify(arrUserInfo);
$.ajax({
//code
});
});
}

You can add validations in another function and return true or false depending on validation result,and call that function on form submit.
function validations()
{
....
for(var i = 0; i < phones.length; i++){
if (!phones[i].value.match(digts)) {
// set error message
return false;
}
}
if(user.value == ''){
// set error message
return false;
}
return true;
}
$('#registration').submit(function(event) {
if(validations())
{
$.ajax({
// code
});
}
else
{
return false;
}
});

Related

Boolean value doesnt change

My JS code:
var name_valid = false;
$("#InputName").blur( function(){
if ($(this).val() != ""){
name_valid = true;
} else {
name_valid = false;
}
});
if (name_valid === true){
alert('ok');
}
console.log(name_valid);
I don't actually understand why my code is not working.
If my <input> is not empty I have to get alert ('ok'), but I don't get anything.
Why my boolean value is still false at the end?
Because it's a callback function, which executes only after the blur function is complete. This means that this line if (name_valid === true) is executing before this line if ($(this).val() != "").
Try changing your code to this:
var name_valid = false;
$("#InputName").blur( function(){
if ($(this).val() != ""){
name_valid = true;
} else {
name_valid = false;
}
if (name_valid === true){
alert('ok');
}
console.log(name_valid);
});
You made a little mistake, you should put your last if statement inside callback function, like below:
var name_valid = false;
$("#InputName").blur(function () {
if ($(this).val() !== "") {
name_valid = true;
} else {
name_valid = false;
}
if (name_valid === true) {
alert('ok');
}
console.log(name_valid);
});
Your conditional only runs on page load. You want it inside the event handler so it runs when the event actually gets triggered
var name_valid = false;
$("#InputName").blur(function() {
if ($(this).val() != "") {
name_valid = true;
} else {
name_valid = false;
}
if (name_valid === true) {
alert('ok');
}
console.log(name_valid);
});
var name_valid = false;
$("#InputName").blur( function(){
if ($(this).val() !== ""){
name_valid = true;
}
if (name_valid === true){
alert('ok');
}
console.log(name_valid);
});
Please try this.
$(document).ready(function () {
var name_valid;
$("input").blur(function () {
if ($(this).val() != "") {
name_valid = true;
} else {
name_valid = false;
}
if (name_valid) {
alert('ok');
}
});
});

How to query multiple conditions or results of anonymous functions in jQuery

First of all, I have a form with several input fields and some Bootstrap-Buttons. Now, what I want to do is to check, if two conditions ("Are all input fields filled?" ; "Is at least one Button pushed down?") are fullfilled to enable the user to click the submit button.
This is my code:
function checkInput() {
var inputFields = $("input[name=inp1],[name=inp2],[name=inp3]");
var buttons = $("button[name=btn1],[name=btn2],[name=btn3]");
var empty1;
var empty2;
buttons.click(function() {
if(!$(this).hasClass('active')) {
empty1 = false;
} else {
empty1 = true;
}
});
inputFields.keyup(function() {
inputFields.each(function() {
if($(this).val().length == 0) {
empty2 = true;
} else {
empty2 = false;
}
});
});
alert(empty1);
alert(empty2);
if(empty1 == true && empty2 == true) {
$('button[name=submitBtn]').prop('disabled', false);
} else {
$('button[name=submitBtn]').prop('disabled', true);
}
}
The alert(...) functions say, that empty1 and empty2 are "undifined", which i can understand. But my question is, how can I retrieve the true or false values from buttons.click() and inputFields.keyup() to query them afterwards?
The problem is the scope of the variables, those vars need to be global:
var empty1;
var empty2;
function checkInput() {
var inputFields = $("input[name=inp1],[name=inp2],[name=inp3]");
var buttons = $("button[name=btn1],[name=btn2],[name=btn3]");
buttons.click(function () {
if (!$(this).hasClass('active')) {
empty1 = false;
} else {
empty1 = true;
}
});
inputFields.keyup(function () {
inputFields.each(function () {
if ($(this).val().length == 0) {
empty2 = true;
} else {
empty2 = false;
}
});
});
alert(empty1);
alert(empty2);
if (empty1 == true && empty2 == true) {
$('button[name=submitBtn]').prop('disabled', false);
} else {
$('button[name=submitBtn]').prop('disabled', true);
}
}
Move it outside of the function an it will works:
see it in jsFiddle working example

JS loop only works when matching to the last element in an array

I cannot get the loop to work in my simple js login script. When i try to login with any login other than the last one in the array (user3 and pass3) it returns false.
What am I doing wrong?
I have tried both == and ===.
var userLogins = [{user:"user1", password:"pass1"},{user:"user2", password:"pass2"},{user:"user3", password:"pass3"}]
var success = null;
function logon(user, pass) {
userok = false;
for (i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
}
else
{
success = false;
}
}
secret(success);
}
function getData() {
var user = document.getElementById("userid").value;
var password = document.getElementById("password").value;
logon(user, password);
}
function secret(auth){
if(auth)
{
show('success');
hide('login');
}
else
{
show('error');
hide('login');
}
}
function show(show) {
document.getElementById(show).className = "show";
}
function hide(hide) {
document.getElementById(hide).className = "hide";
}
for (i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
}
else
{
success = false;
}
}
You need a break in there, otherwise your true value for success simply gets overwritten with false on the next iteration... except for the last possible credentials, for which there is no "next" iteration.
Once you've done that, you don't actually need the else branch at all:
var success = false;
for (i = 0; i < userLogins.length; i++) {
if (pass == userLogins[i].password && user == userLogins[i].user) {
success = true;
break;
}
}
Use break when you found it. Otherwise the next loop will set success to false.
for (var i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
break;
}
else
{
success = false;
}
}
secret(success);

Client-side RadioButtonList validation

function IsChecked()
{
var rblActive = document.getElementById("<%=rblActive.ClientID %>");
var item = rblActive.getElementsByTagName("input");
var IsItemChecked = false;
for (var i = 0; i < item.Length; i++)
{
if (item[i].checked)
{
IsItemChecked = true;
}
}
if (IsItemChecked == false)
{
alert("Check Yes or No");
rblActive.focus();
return false;
}
return true;
}
This is the code I tried. When control comes in the for loop, it directly comes out without any action even if the item in the radio button list is checked or not checked.
You can do the same with jQuery also..
function ValidateControls() {
var count = 0;
$("input[type=radio]").each(function () {
if ($(this).attr('checked')) {
count++;
}
});
if (count > 0) {
return true;
}
else {
alert("No Row Selected");
return false;
}
}

retain form values onclick after javascript validation fails

This is part of an assignment. Everything that's supposed to work, already works, but there's something that bothers me. The only purpose of the code so far is to test our ability to validate from data. Anyway, right now the validate() function is attached to a submit button:
<input type="submit" value="Find Love" onclick="validate()">
When any validation fails, all the text boxes, drop downs, etc. are cleared, but I want them to retain their values and just focus on the first incorrect value (retaining their values is more important to me at this point). The actual Does that require some modification of the onclick function or a different function all together? Please help. If you need to see the javascript I can post that as well.
function validate()
{
var blnValid = true;
if(isBlank("txtFName"))
{
blnValid = false;
alert("First name cannot be blank!")
document.getElementById("txtFName").focus();
}
if(blnValid)
{
if(isBlank("txtLName"))
{
blnValid = false;
alert("Last name cannot be blank!")
document.getElementById("txtLName").focus();
}
}
if(blnValid)
{
if(isBlank("txtAge"))
{
blnValid = false;
alert("Age cannot be blank!")
document.getElementById("txtAge").focus();
}
}
if(blnValid)
{
var strInput = document.getElementById("txtAge").value;
if(!isInt(strInput))
{
blnValid = false;
alert("You must enter a valid number in the age field.")
document.getElementById("txtAge").select();
}
}
if(blnValid)
{
if(document.getElementById("selUserGender").selectedIndex <= 0)
{
alert("Please select your gender");
blnValid = false;
}
}
if(blnValid)
{
if(document.getElementById("selFindGender").selectedIndex <= 0)
{
alert("Please select your gender");
blnValid = false;
}
}
if(blnValid)
{
blnChecked = false;
arRadio = document.forms[0].rdbAgeRange;
for (var i = 0; i < arRadio.length; i++)
{
if(arRadio[i].checked)
{
blnChecked = true;
break;
}
}
if (!blnChecked)
{
alert("You must select an age group.");
blnValid = false;
}
}
if(blnValid)
{
if(!document.getElementById("chkSkeeball").checked
&& !document.getElementById("chkAir").checked
&& !document.getElementById("chkCliff").checked
&& !document.getElementById("chkHamster").checked)
{
blnValid = false;
alert("You must select a hobby.")
}
}
return blnValid;
}
function isInt(strValue)
{
var validNums = "0123456789";
var blnIsNumber = true;
var tempChar;
for (var i = 0; i < validNums.length; i++)
{
tempChar = strValue.substr(i, 1);
if (validNums.indexOf(tempChar) == -1)
{
return false;
}
}
return true;
}
function isBlank(elementID)
{
if(document.getElementById(elementID).value.length == 0)
{
return true;
}
return false;
}
Your problem is actually your HTML. Nothing in your Javascript is going to clear the elements but because you're using onClick the form is actually submitting anyway. I assume that it probably just submits back to the page and clears everything. Instead of onClick use onSubmit in the form element:
<form method="post" action="url_of_action" onSubmit="return validate()">
If it's not valid it will prevent the form from submitting.
Missing semi-colons:
if(isBlank("txtFName"))
{
blnValid = false;
alert("First name cannot be blank!") //here
document.getElementById("txtFName").focus();
}
if(blnValid)
{
if(isBlank("txtLName"))
{
blnValid = false;
alert("Last name cannot be blank!") //and here
document.getElementById("txtLName").focus();
}
}
if(blnValid)
{
if(isBlank("txtAge"))
{
blnValid = false;
alert("Age cannot be blank!") //and here
document.getElementById("txtAge").focus();
}
}

Categories

Resources