Simple "Math" CAPTCHA

Angus Y. picture Angus Y. · Nov 23, 2016 · Viewed 10.9k times · Source

everyone. I am a jquery beginner and want to ask a few questions.

I am coding a simple math captcha for form submission test, I wanna generate a set of new random number each time when I press the "reset button".

But I when I google for the solution, most are trying to reload the page or reload the whole function, So I wanna ask if there is a way to do this.

And I would be very pleased if you guys can help me improving the codes as I think I am writing quite dummy. Thanks so much!!!

Please have a look at my code in fiddle :) https://jsfiddle.net/v7bcjj1q/#&togetherjs=2nOVnkI34j

my code:

$(document).ready(function(){

    $('button[type=submit]').attr('disabled','disabled');

    var randomNum1;
    var randomNum2;

    //set the largeest number to display

    var maxNum = 20;
    var total;

    randomNum1 = Math.ceil(Math.random()*maxNum);
    randomNum2 = Math.ceil(Math.random()*maxNum);
    total =randomNum1 + randomNum2;

    $( "#question" ).prepend( randomNum1 + " + " + randomNum2 + "=" );

    // When users input the value

    $( "#ans" ).keyup(function() {

        var input = $(this).val();
        var slideSpeed = 200;

        $('#message').hide();

        if (input == total) {

            $('button[type=submit]').removeAttr('disabled');
            $('#success').slideDown(slideSpeed);
            $('#fail').slideUp(slideSpeed);

        }

        else {

            $('button[type=submit]').attr('disabled','disabled');
            $('#fail').slideDown(slideSpeed);
            $('#success').slideUp(slideSpeed);

        }

    });

    // Wheen "reset button" click, generating new randomNum1 & randomNum2
});

Answer

Me.Name picture Me.Name · Nov 23, 2016

For re-usability, a separate function can be used to generate the question

var total;

function getRandom(){return Math.ceil(Math.random()* 20);}
function createSum(){
        var randomNum1 = getRandom(),
            randomNum2 = getRandom();
    total =randomNum1 + randomNum2;
  $( "#question" ).text( randomNum1 + " + " + randomNum2 + "=" );  
  //in case of reset
  $('#success, #fail').hide();
  $('#message').show();
}

Inside the document load, the function can be called to initialize and subsequently attached to the click event

$(document).ready(function(){

    $('button[type=submit]').attr('disabled','disabled');

    //create initial sum
    createSum();
    // On "reset button" click, generate new random sum
    $('button[type=reset]').click(createSum);

    //....

One step further would be to set the visibility in a function that (re)checks the input on both keyup and reset. Example fiddle