Why does this "IF" always execute even the condition is false? - javascript

This is my code:
$('.btn-back').off('click').on('click', function (event) {
var valid = carInfo.validate();
if (valid) {
event.preventDefault();
}
});
the sentence event.preventDefault() always executes no matter what value valid is.
When I change the code to
$('.btn-back').off('click').on('click', function (event) {
var valid = carInfo.validate();
if (valid) {
event.preventDefault();
} else {
}
});
it runs the way it should be. Maybe it's something related to Automatic Semicolon Insertion (ASI).

Use the jQuery Validation plugin way:
carInfo.validate() will return Validator object.
So valid variable is always true. Use valid method from docs:
$('.btn-back').off('click').on('click', function (event) {
carInfo.validate();
if (carInfo.valid()) {
event.preventDefault();
}
});

Related

Unexpected token

I have the following to check a few form inputs (will be part of a larger validation) but the console shows unexpected token for the first line.
$( document ).ready(function() {
$('.contactcheck').submit(function) {
var abort = false;
$('#name,#make,#model,#year,#email,#contactmeth').each(function() {
if ($(this).val()==='') {
$(this).addClass(' error');
abort = true;
}
})
if (abort) { return false; } else { return true; }
})
});
Anyone able to point me in the direction of what is wrong? Looks valid to me.
You forgot the open parenthesis after function.
Replace:
$('.contactcheck').submit(function) {
With:
$('.contactcheck').submit(function() {
On a separate note you could simplify your code if you do this:
return abort;
Instead of:
if (abort) { return false; } else { return true; }
jQuery's submit expects a function. Function expressions look like this:
function () {}
So change your code to
$('.contactcheck').submit(function () {
It's the same as in $(document).ready(function () { ... }).

Why isnt my value being returned in jquery?

I have created a validate() function in JavaScript, and when I invoke the method it returns undefined .... everything in my code looks right to me, why is it doing that?
function validate() {
var __self = this;
__self.is_valid = true;
$(document).on("click", "#login,#create_account", function() {
var email = $("#email").val(),
password = $("#password").val();
if (email == "") {
$("#email-err-msg").removeClass("hidden").html("Enter an email address");
__self.is_valid = false;
} else {
$("#email-err-msg").addClass("hidden")
}
return __self.is_valid;
});
}
(function logUser() {
$(document).on("submit", "form", function() {
var action = $(".action").attr("data-account-action");
console.log(validate());
if (!validate()) {
return false;
}
});
})();
Your validate function never returns anything, so the result of calling it is always undefined. You have a callback to an event handler that you define within it, and you have a return statement in that, but none in validate.
It's not clear why you are hooking up an event handler every time the user tries to submit a form. I would suggest not doing that. Perhaps something like:
function validate() {
var is_valid = true;
var email = $("#email").val(),
password = $("#password").val();
if (email == "") {
$("#email-err-msg").removeClass("hidden").html("Enter an email address");
is_valid = false;
} else {
$("#email-err-msg").addClass("hidden")
}
return is_valid;
}
(function logUser() {
$(document).on("submit", "form", function() {
var action = $(".action").attr("data-account-action");
return validate();
});
})();
I've removed the click event handler as I couldn't see that there was any reason for it, removed the global variable __is_valid,1 and returns the result of calling validate directly from the submit handler (since returning true is harmless).
1 Why was it a global variable? Because you were calling validate like this: validate(), which means that within the call, this refers to the global object (unless you're using strict mode, in which case it would be undefined; but I know you aren't because you said it returned undefined rather than throwing an error). Adding properties to the global object creates global variables.

Prototype. Restrict input to numbers

I have multiple inputs to which i am attaching event listener that listens to what key was pressed, tests it with regular expression and returns true if number and false if other charachter. The problem is that input is accepting letters even if my test function returns false.
$$(".number").each(function (element) {
return $(element).observe("keypress", function (event) {
return /[\d\s]/.test(String.fromCharCode(event.keyCode));
});
});
Example on JS Bin.
You are using prototypeJS, which as far as I know doesn't allow to use return false to cancel event propagation and default behavior (As jQuery does). Though it has Event.stop(event) method
$$(".number").each(function (element) {
return $(element).observe("keypress", function (event) {
var result = /[\d\s]/.test(String.fromCharCode(event.keyCode));
if (!result) {
Event.stop(event);
}
});
});
Event.stop(event)
You can do it by testing the value on keyup, then removing whatever was entered if it doesn't match your desired pattern:
$$(".number").each(function (element) {
return $(element).observe("keyup", function (event) {
var val = this.value
if(!/[\d\s]/.test(String.fromCharCode(event.keyCode))){
this.value = val.substring(0, val.length - 1);
}
});
});

Is it possible to get a return type from a keyup function?

My current code is this and what I'm trying to is see if I could get a return value after the key up is done.
$("#confirm").keyup(function(event){
event.preventDefault();
ajax_pass_check();
});
so I would end up with something like this because my ajax_pass_check(); function returns true/false.
$("#confirm").keyup(function(event){
event.preventDefault();
return ajax_pass_check();
});
I would like to see if I could do that, and try something like
var one = $("#confirm").keyup(function(event){
event.preventDefault();
return ajax_pass_check();
});
I'm new to javascript and I've looked on google for awhile and I haven't found what I needed so I thought I'd ask. However when I did try that, I didn't get the expected result I was hoping for. Since var one remained false, when it should have been true after the function ajax_pass_check();
~edit: I took advice one of you guys (thanks for all the replies!) I still can't figure out why my var one variable false even though I set it to true in the keyup function.
$(document).ready(function(){
var one = false;
$("#confirm").keyup(function(event){
event.preventDefault();
one = ajax_pass_check();
//one = true; //even if I do that it doesn't work.
});
if(one == true)
{
$('input[type="submit"]').removeAttr('disabled');
}
else
{
$('input[type="submit"]').attr('disabled','disabled');
}
});
Instead of returning a value, you should consider using global scope for the variable, and set its desired value inside your function:
var wasSuccessful = false;
$("#confirm").keyup(function(event){
event.preventDefault();
your_function();
});
function yourfunction() {
if your awesome code worked { wasSuccessful = true; }
else { wasSuccessful = false; }
}
No, but you could call another function to use the result of ajax_pass_check. For example,
$("#confirm").keyup(function(event){
event.preventDefault();
doSomethingElse(ajax_pass_check());
});
function doSomethingElse(keyUpOk) { // Do something ... }
Assuming (based on your function names) you are using this to do some form of validation this will allow you to display or clear an error message.
The reason you cant do
var one = $("#confirm").keyup(function(event){
event.preventDefault();
return ajax_pass_check();
});
is because the key up function is just binding you function to the event, so this code will have already been executed when the key is released. You will probably want to call a function so that something is done with the result of the keyup event handler after the keyup event is fired, not when you function is bound to the event.
Try this instead
$(document).ready(function(){
var one = false;
$("#confirm").keyup(function(event){
event.preventDefault();
one = ajax_pass_check();
//one = true; //even if I do that it doesn't work.
if(one == true)
{
$('input[type="submit"]').removeAttr('disabled');
}
else
{
$('input[type="submit"]').attr('disabled','disabled');
}
});
});
The Answer is: No
The jQuery Function keyup doesnt return a special value, only the jQuery Object see the API(at the top), since it is used only to bind functions.
Depence on what you want to achieve, one of the solutions, mentioned by the others could solve your issue.

Detecting if onsubmit was cancelled by another event handler?

I would like a way of detecting/triggering a function when the form onsubmit is cancelled by any onsubmit handler. What's the most reliable method for doing this?
Wrap it up...
// This code should execute last (after onsubmit was already assigned)
var oldsub = document.forms[0].onsubmit;
document.forms[0].onsubmit = function() {
if(!oldsub)
alert("Onsubmit did not exist!");
else if(oldsub())
alert("Onsubmit passed!");
else
alert("Onsubmit failed!");
}
you could override all the forms' onsubmit handlers with your own:
var f = document.getElementById('myForm'); // or whatever
if (f.onsubmit) {
var oldSubmit = f.onsubmit;
f.onsubmit = function () {
var result = oldSubmit.call(this);
if (result === false) {
alert("Cancelled.");
}
return result;
};
}
I'm probably wrong, but would returning false on one handler cancel the stack? Failing that, you could attach a check call on each event to check whether another one in the stack canceled.

Categories