Landslyde Landslyde - 4 years ago 121
Javascript Question

Am I using this JQuery function the right way?

I made up a simple CAPTCHA using JQuery. And while it works fine, I don't think I'm doing it the right way.

When the page loads, the function is called:

getAnswer(answer);


Which is:

function getAnswer(){
var min = 0;
var max = 50;
var ranNum1 = Math.floor(Math.random() * (max - min + 1)) + min;
var ranNum2 = Math.floor(Math.random() * (max - min + 1)) + min;
$('#ran1').html(ranNum1).show();
$('#plus').html("+").show();
$('#ran2').html(ranNum2).show();
answer = ranNum1 + ranNum2;
}


And when I compare
answer
to the user input,

if(answer != captcha){
$('#captchaErr').html("CAPTCHA is Incorrect").show().delay(3000).fadeOut("slow");
$('#captcha').focus();
return false;
}


it works. But in looking at a lot of Q&A regarding this here on SO, it seems like I shld use a
return
in the function. So when I put a
return
in the
function
, it also works. Since it works both ways, is one any better (or a better practice) than the other? Just wondering.

Answer Source

You don't need to return any value.

First of all, rename your function to showQuestion or something; as name suggest, it only shows question and it's not getter. answer variable should be stored somewhere - not recommended is global variable, but you can pack ran1, plus and ran2 into one DIV, and set data field:

$(document).ready(function() {
  showQuestion();
}

Last line in showQuestion:

$('#question').data('answer', answer);

OR you can leave function name like getQuestion(), return correct answer and set it in ready() function.

When you want to validate, simply get answer:

var answer = $('#question').data('answer');

Note that's local variable, not global.

Of course you know that captcha can't be client-side?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download