Boolean value doesnt change - javascript

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

Related

Validation. Checking and calling a function

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

Showing multiple validation alert on button click

I have written a Jquery code for validation. But the problem here is that, First the regular expression message fires and after that requiredField error message fires.
Here is my code:-
var ErrArr = [];
$(document).ready(function () {
$('#btnSave').click(function (e) {
e.preventDefault();
validateTextBoxes();
function FunValidatePan()
if (ErrArr.length > 0)
{
alert(ErrArr.join("\n"));
ErrArr = [];
return false;
}
});
function validateTextBoxes() {
if ($("#txtPanNo").val() === "") {
ErrArr.push('Pan No is required');
}
}
function FunValidatePan() {
var StrPriError = "";
if (Trim(document.getElementById("txtPanNo").value) != "" && Trim(document.getElementById("txtPanNo").value) != "NULL") {
var fil = /^[a-zA-Z0-9]+$/;
if (fil.test(document.getElementById("txtPanNo").value)) {
var abc = Trim(document.getElementById("txtPanNo").value);
if (abc.length != 10) {
StrPriError += ' Enter valid PAN Card\n';
}
}
else {
StrPriError += ' Enter valid PAN Card\n';
}
}
if (StrPriError != "") {
alert(StrPriError);
return false;
}
else {
return true;
}
}
I want that in single message. How to achieve that. Please suggest. Also I want that in Jquery
UPDATE
ASPX
<asp:TextBox ID="txtPanNo" runat="server" Width="100" MaxLength="10"></asp:TextBox>
Please check changes in the above code.
var ErrArr = [];
$(document).ready(function () {
$('#btnSave').click(function (e) {
e.preventDefault();
validateTextBoxes();
FunValidatePan();
if (ErrArr.length > 0)
{
alert(ErrArr.join("\n"));
ErrArr = [];
return false;
}
});
function validateTextBoxes() {
if ($("#txtPanNo").val() === "") {
ErrArr.push('Pan No is required');
}
}
function FunValidatePan() {
if (Trim(document.getElementById("txtPanNo").value) != "" && Trim(document.getElementById("txtPanNo").value) != "NULL") {
var fil = /^[a-zA-Z0-9]+$/;
if (fil.test(document.getElementById("txtPanNo").value)) {
var abc = Trim(document.getElementById("txtPanNo").value);
if (abc.length != 10) {
ErrArr.push('Enter valid PAN Card');
}
}
else {
ErrArr.push('Enter valid PAN Card');
}
}
}

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

Clearing setTimeout issues

I'm trying to set "mouseactive" to true less than a second after a key command, but I would like to cancel that action if the key is pressed within that time period. However I can't seem to figure out how to do this. This is what I have...
$(window).keydown(function(e) {
if (e.keyCode == 40) {
e.preventDefault();
mouseactive = false;
clearTimeout(t);
var t = setTimeout("mouseActive()",800);
} else if (e.keyCode == 38) {
e.preventDefault();
mouseactive = false;
clearTimeout(t);
var t = setTimeout("mouseActive()",800);
}
});
function mouseActive() {
mouseactive = true;
}
But this doesn't work, it doesn't set mouseactive back to true... can anyone tell me what I'm doing wrong here?
Edit: Cleaned up redundant code.
More Edits: Make sure your var t is defined outside any closure including $(document).ready. See below,
var t = null;
$(document).ready(function () {
//..below code except for var t = null
});
Declare var t outside the handler.
var t = null;
$(window).keydown(function(e) {
e.preventDefault();
if (e.keyCode == 40) {
mouseactive = false;
} else if (e.keyCode == 38) {
mouseactive = false;
}
if (t != null) clearTimeout(t);
t = setTimeout(mouseActive, 800);
});
function mouseActive() {
mouseactive = true;
}
Your problem is that t is not in scope the 2nd time the function runs. You need to make t a global variable .
var t;
$(window).keydown(function(e) {
if (e.keyCode == 40) {
e.preventDefault();
mouseactive = false;
clearTimeout(t);
t = setTimeout(mouseActive,800);
} else if (e.keyCode == 38) {
e.preventDefault();
mouseactive = false;
clearTimeout(t);
t = setTimeout(mouseActive,800);
}
});
function mouseActive() {
mouseactive = true;
}
P.S. Don't pass strings to setTimeout, pass functions. It uses eval when you pass strings.
you are redeclaring "t" all the time, try this:
var t = null;
$(window).keydown(function(e) {
if (e.keyCode == 40) {
e.preventDefault();
mouseactive = false;
if(t != null)
{
clearTimeout(t);
}
t = setTimeout("mouseActive()",800);
} else if (e.keyCode == 38) {
e.preventDefault();
mouseactive = false;
if(t != null)
{
clearTimeout(t);
}
t = setTimeout("mouseActive()",800);
}
});
function mouseActive() {
mouseactive = true;
}

Javascript Focus Is Not Working on Aspx Page

Hy Guys,
Please Look at the code and Try to Help Out. The function ive written is not working but its RUNNING properly. Its about To set focus on next content on page im using it on an ASPX page. Heres my code Below :
function SetFocusOnSave(CTag,NTag)
{
alert('Running'+CTag+NTag);
var CurrentTag=document.getElementById(CTag);
var NextTag = document.getElementById(NTag);
if ( (event.keyCode==13)||(event.keyCode==9) )
{
if(CurrentTag.value=="")
{
alert("Please Enter Detail First");
CurrentTag.focus();
}
if(CurrentTag.value!="")
{
event.returnValue=true;
document.getElementById(NextTag).focus();
}
}
}
snametxt.Attributes.Add("onkeypress",
SetFocusOnSave('<%=snametxt.ClientID%>','<%=sdesctxt.ClientID%>');");
have you tried to replace
document.getElementById(NextTag).focus();
with
NextTag.focus();
?
You have to add return false; after you found the false in validation otherwise the flow will continue till end.
Try this function:
function SetFocusOnSave(CTag, NTag) {
alert('Running' + CTag + NTag);
var CurrentTag = document.getElementById(CTag);
var NextTag = document.getElementById(NTag);
if ((event.keyCode == 13) || (event.keyCode == 9))
{
if (CurrentTag.value == "")
{
alert("Please Enter Detail First");
CurrentTag.focus();
return false;
}
if (CurrentTag.value != "") {
event.returnValue = true;
NextTag.focus();
return false;
}
}
};
Hy Guys Ive Tried A NEW CODE AND Fortunately Its Working Fine Here its my Code
function Navigation(CTag, NTag, Number) {
var CurrentTag = document.getElementById(CTag);
var NextTag = document.getElementById(NTag);
var IsNumber = Number; //Checking if value is number
if (NextTag.disabled == true) {
NextTag.disabled = false;
NextTag.className = "txt";
}
if (event.keyCode == 9) {
CurrentTag.focus();
event.returnvalue = false;
}
if (event.keyCode != 9) {
if (event.keyCode == 13) {
if (IsNumber == "Y") {
if (NextTag.disabled == true) {
NextTag.disabled = false;
}
if (CurrentTag.value != "") {
NextTag.focus();
event.returnvalue = true;
}
if (CurrentTag.value == "") {
alert('Please Enter Value To Proceed Further.');
CurrentTag.focus();
event.returnvalue = false;
}
if (isNaN(CurrentTag.value)) {
alert("Please Enter A Valid Number");
CurrentTag.value = "";
CurrentTag.focus();
}
}
if (IsNumber == "N") {
if (CurrentTag.value == "") {
alert('Please Enter Value To Proceed Further.');
CurrentTag.focus();
event.returnvalue = false;
}
if (CurrentTag.value != "") {
NextTag.focus();
event.returnvalue = true;
}
}
}
}
};
Thanks ya'll !! :)

Categories

Resources