1
$("#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.

Shiladitya
  • 12,003
  • 15
  • 25
  • 38

2 Answers2

2

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?

Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
  • alright i think it works, thanks, another way i found how to do this, someone posted it here but deleted it, i think, was with preventDefault. but i like your way better :) – Erick Vazovsky Jul 10 '18 at 13:51
  • and yes it looks weird because its jsut a part of code, the part that was giving me trouble – Erick Vazovsky Jul 10 '18 at 13:51
  • @ErickVazovsky Yes, he deleted it because there was some false statement and `preventDefault()` is not exactly the same as `return false`. Here's his code: https://pastebin.com/raw/mebUwMEs – Karl-André Gagnon Jul 10 '18 at 13:57
0

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;

})
AB Udhay
  • 643
  • 4
  • 9