0

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
});
fuzzy
  • 97
  • 6
Angus Y.
  • 3
  • 1
  • 1
  • 2
  • Just set up an event listener for a click on the reset button. On click, you'll perform the same calculations you've already done for `randomNum1`, `randomNum2`, and `total`. – Gavin Nov 23 '16 at 15:22
  • Umm... I know i am necromanting this, but -- are you sure this actually work? I, as simple brute-force robot, really dont care about your `$('button[type=submit]').attr('disabled','disabled');`, (I am pretty sure I dont even run any javascript, why would I :) ) I just try to find where your form is posted and start hammering it with dictionary - and your js captcha cant stop me, becouse I will completely skip your html (just parse it first time to find input names and where your form is submited). I am pretty sure this captcha is only annoying to real guys&gals and non-existent for real robot. – Jan 'splite' K. Mar 11 '20 at 13:08
  • (just adding becouse this SO question is on first page when googling "math captcha" and this can turn out very badly for someone somewhere) – Jan 'splite' K. Mar 11 '20 at 13:14

3 Answers3

3

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

Me.Name
  • 12,259
  • 3
  • 31
  • 48
1

Just add an onClick event on the reset button

Inside you have to generate new numbers, total, clear question and clear input

$('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
$("#reset").on("click", function() {
  randomNum1 = Math.ceil(Math.random() * maxNum);
  randomNum2 = Math.ceil(Math.random() * maxNum);
  total = randomNum1 + randomNum2;
  $("#question").empty();
  $("#ans").val('');
  $("#question").prepend(randomNum1 + " + " + randomNum2 + "=");
});
* {
  padding: 0;
  margin: 0;
}
html,
body {
  font-family: 'Open Sans';
  font-weight: lighter;
  font-size: 12px;
  width: 100%;
  height: 100%;
}
#success,
#fail {
  display: none;
}
#message,
#success,
#fail {
  margin-top: 10px;
  margin-bottom: 10px;
}
.container {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
p {
  display: inline;
  margin-right: 5px;
}
input,
button {
  font-family: 'Open Sans';
  font-weight: lighter;
  font-size: 12px;
}
input {
  border: 1px solid #FFBBD7;
  width: 30px;
  height: 20px;
  text-align: center;
}
button {
  border: none;
  border-radius: 1.5em;
  color: #FFF;
  background: #FFBBD7;
  padding: 2.5px 10px;
  width: 75px;
  height: 30px;
  cursor: pointer;
  transition: background .5s ease-in-out;
}
button:hover:enabled {
  background: #303030;
}
button:disabled {
  opacity: .5;
  cursor: default;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="question"></p>
<input id="ans" type="text">
<div id="message">Please verify.</div>
<div id="success">Validation complete :)</div>
<div id="fail">Validation failed :(</div>
<button type="submit" value="submit">Submit</button>
<button type="reset" id="reset" value="reset">Reset</button>
Weedoze
  • 13,683
  • 1
  • 33
  • 63
0

You can do it like this, add this piece of code:

$('#reset').click(function(e){
  randomNum1 = Math.ceil(Math.random()*maxNum);
  randomNum2 = Math.ceil(Math.random()*maxNum);
  total =randomNum1 + randomNum2;
   $( "#question" ).html( randomNum1 + " + " + randomNum2 + "=" );
});

#reset is in this case your reset button. You should just give it that ID, or change the selection depending on what you like most. On click, you'll reset the variables, and change the HTML from the question.

I did it by just duplicating the code, but you might want to create a single function for it, as you are using it multiple times.

Hespen
  • 1,384
  • 2
  • 17
  • 27
  • Thanks!! I do think it is a way to solve. But if I get more and more variables such as variable for different rotation degrees and different colors, it will be tedious as a have to all the variable again in the click function. So, is there any other methods to write it in a " cleaner" way?:) – Angus Y. Nov 23 '16 at 15:37
  • Option 1: Create a new function, call it reset() for example. In that reset function you place everything you need to assign the variables. Whenever you load the page, or whenever you reset the form, call that reset() function. Option 2: If you're applying the same function to fill multiple variables, you could always create an array of those variables, and loop through it. Option 3: Or create an object for everything you need (like classes in java), put those in an array, and give those objects a function called Reset – Hespen Nov 23 '16 at 15:53