jQuery refreshes page even with return false - javascript

$("#submit").click(function()
{
function checkZeros()
{
if ([0] == 0) {
if ([1] != '.') {
alert("alert message");
return false;
}
}
}
checkZeros($("#user-input-currency").val());
if(!$.isNumeric($("#user-input-currency").val())) {
alert("Please provide price in numeric value");
return false;
}
})
I have function that checks if user-input-currency first number is 0 followed with '.' if not then gives alert, and returns false so the user can input right value. but in my case I get the alert message but page still refreshes.
what could be the problem here?
The next code that checks isNumeric works correct returns alert message and doesnt refreshes page.

Your return is in another scope than your click handler, so even if checkZeros returns false, your click handler wont stop.
You can use the following instead:
if(checkZeros($("#user-input-currency").val() === false)) return false;
The strict comparison here is used since your function doesn't have a return trueand functions returns undefined by default.
You can, for a better readability, change your function so it always returns a boolean and simplify your if to:
if(checkZeros($("#user-input-currency"))) return false;
p.s.: your code doesn't make sense, is it pseudo code?

Your click handler callback is not returning any value as only the checkZeros function is returning false value.
So you have to return the value which checkZeros function is returning to the click handler so that it won't proceed to submit.
$("#submit").click(function() {
function checkZeros() {
if ([0] == 0) {
if ([1] != '.') {
alert("alert message");
return false;
}
}
}
if (!$.isNumeric($("#user-input-currency").val())) {
alert("Please provide price in numeric value");
return false;
}
// in your case checkZeros function returns false, a function explicitly returns undefined if you haven't return any value, so you have to use conditional operator here
return !checkZeros($("#user-input-currency").val()) ? false : true;
})

Related

cancelling alert poppup in javascript

Consider this code:
function reason(id) {
var reason = prompt("State reason");
while (!reason.trim()) {
reason = prompt("Please enter text");
}
document.getElementById(id).value = reason;
return true;
}
It works perfectly fine, but when I want to get rid of the poppup by pressing escape for example, the function returns true because the form executes. What should I do to make it do nothing if I close/cancel the poppup?
... the function returns true because the form executes. What should I do to make it do nothing if I close/cancel the poppup?
It depends entirely on how you call your reason function, but if you want reason to return false when prompt is cancelled, then:
function reason(id) {
var reason = prompt("State reason");
while (reason !== null && !reason.trim()) { // *** Changed
reason = prompt("Please enter text");
}
if (reason === null) { // *** Added
return false; // *** Added
} // *** Added
document.getElementById(id).value = reason;
return true;
}
prompt returns null when you cancel it.
But again, it's up to what calls reason to do something appropriate with the true or false.
Side note: You can call your function and a variable inside it by the same name, but it's not a great idea. If it's a habit, you'll end up making writing recursive functions quite difficult...

Javascript Issue Checking if Value is Even

I'm trying to write a function that checks whether a value is odd or even, but it isn't quite working as it should, or rather, at all.
The code I got was from this question.
function isEven(value) {
if (value % 2 == 0) {
return true;
console.log("True");
}
else {
return false;
console.log("False");
}
console.log(value);
}
isEven(3);
I get no errors in the browser's console, but it also does not log True, False, or value.
Note: I will also accept jQuery solutions, but would prefer Javascript.
You are returning before logging. Anything after return will not be executed.
return after logging
function isEven(value) {
if (value % 2 == 0) {
console.log("True");
return true;
} else {
console.log("False");
return false;
}
}
isEven(3);
Ensure value is an integer first by parsing it with
parseInt(value)

Multiple return in function not working

I have many function inside one main function validate which doesn't work for some reason.However if the function validate contain a single function it works
function validate() {
return textcheck("txtname");
return numcheck("txtnum");
// textcheck and numcheck function are here
//doesn't work
}
function validate() {
return textcheck("txtname");// works fine
}
function validate() {
return numcheck("txtnum"); // works fine
}
why does 2 return inside a function don't work
Why it doesn't work
return exits a function, so code after the first return will never run.
Consider these functions:
function logs() {
console.log('I have been called');
return;
}
function doesNotLog() {
return;
console.log('I will not be called');
}
The first function does log a message to the console because console.log is called before return.
The second function doesn't, because return exits the function before console.log is called.
Fixing your example
If you want to return true if both textcheck and numcheck return a truthy value, you could use the logical AND operator &&:
// Returns true if both checks pass
function validate() {
return textcheck("txtname") && numcheck("txtnum");
}
If you need either of the two tests to pass, use the OR operator ||:
// Returns true if either check passes
function validate() {
return textcheck("txtname") || numcheck("txtnum");
}
If you want to return the status of each individual check, you could return an object:
function validate() {
return {
textCheck: textcheck("txtname"),
numCheck: numcheck("txtnum")
}
}
return exits the function when it's encountered, so your second return will never be reached.
If your goal is to return a truthy value* if either of two function calls returns a truthy value, you can use ||:
function validate() {
return textcheck("txtname") || numcheck("txtnum");
}
That calls textcheck and, if it returns a truthy value, returns that value; if textcheck returns a falsey value, it calls numcheck and returns its result.
If you want to return a truthy value if both of two functions returns a truthy value, you can use &&:
function validate() {
return textcheck("txtname") && numcheck("txtnum");
}
That calls textcheck and, if it returns a falsey value*, returns that value; otherwise it calls numcheck and returns its result.
I suggest working through some basic JavaScript tutorials.
* "truthy value" and "falsey value": JavaScript's && and || operators don't always result in true or false like they do in many other languages. Instead, they look for "truthy" values (values that coerce to true) or "falsey" values (values that coerce to false). The falsey values are 0, "", NaN, null, undefined, and of course, false; the truthy values are everything else.
Return in function terminate him.
If you want to validate two (or more) values use one return statement.
function validate() {
return textcheck("txtname") && numcheck("txtFname");
}
This solution may help you if you need to return 2 values at the same time. You just need to return a json object
function validate() {
return {
txtname : textcheck("txtname"),
txtnum : numcheck("txtnum")
}
}
After you call the function, you can get your values like this :
var result = validate();
// result.txtname
// result.txtnum
Looking at your code, I assume you want the validate() return you success (true) if both textcheck() and numcheck() succeed. Try this -
function validate() {
return textcheck("txtname") &&
numcheck("txtnum");
}

check multiple input values with javascript and marking multiple input boxes on 1 check

I expected the following function to apply a red border to BOTH the input field with id 'name', AS the input field with the id 'email'. (when the user leaves all input-fields empty)
However, the script only applies the red border to the input-field with id 'name', and leaves the field with id 'email' untouched.
function checkform() {
if ( name() && mail() ) {
return true;
} else {
return false;
}
}
function name() {
if (document.getElementById("name").value == "") {
$("#name").css("border", "1px solid red");
return false;
} else {
return true;
}
}
function mail() {
if (document.getElementById("email").value == "") {
$("#email").css("border", "1px solid red");
return false;
} else {
return true;
}
}
It seems like the return false in the sub-function 'name()' somehow 'kills' the entire code, and stops 'mail()' from every being run.
Update:
If I switch the function-names in the 2nd line only the input-field with id 'email' gets a red border (if user leaves all input-fields empty).
Then the field with id 'name' remains untouched.
(Sorry for using javascript and jquery at the same time)
If statement runs the conditions one by one until it is sure that they don't fulfill the condition. In your case if name() is false it will never run the conditions after it. In your case you can try using something like:
function checkform() {
var isValid = name();
isValid = mail() && isValid;
return isValid;
}
However I recommend you to write a generic function that will check if some input given as parameter is empty.
Also there is quite nice jQuery plugin that might help you with your task: http://jqueryvalidation.org/
The return false statement in the name function is short-circuiting the statement inside the if condition.
While evaluating if( name() && mail() ), name() returns false and since AND with false always gives false, the statement is short-circuited and the mail() function is never called.

Use confirm() as a condition to if?

I have this function:
function RemoveProduct() {
if (confirm("Poista?") == return true) {
return true;
} else {
return false;
}
}
When you click a "remove" button on the page, it should ask if it should remove a product, and if the answer is yes, it will remove it.
But as far as I know, I can't use another brackets on the if sentence conditions?
How this should be done?
When you compare a return value to true you shouldn't use return true, just true:
function RemoveProduct() {
if (confirm("Poista?") == true) {
return true;
} else {
return false;
}
}
You don't even need to do the comparison, as the result from confirm is a boolean value:
function RemoveProduct() {
if (confirm("Poista?")) {
return true;
} else {
return false;
}
}
And you don't even need the if statement, you can just return the result from confirm:
function RemoveProduct() {
return confirm("Poista?");
}
Remember to use return when you use the function in an event. Example:
<input type="submit" onclick="return RemoveProduct();" />
confirm() returns a boolean value and you can return that. Like so:
function RemoveProduct() {
return confirm("Poista?");
}
But as far as I know, I can't use another brackets on the if sentence
conditions?
There is nothing that prevents you from executing a function within an if condition. That said, I always get all the arguments to my conditional settled before the if, for clarity and readability.
Here is your code greatly simplified.
var confirmed = confirm('whatever');
return confirmed;
just use
<a onclick="return confirm('ARe sure want to remove');">remove</a>

Categories