Jiang Lan Jiang Lan - 5 months ago 9
HTML Question

How to set the limit for a form's submit time in jQuery

I'm creating a little game: "guess a number"

Here is the code in jsFiddle: Guess Number

What I want is to set the limit for guess time, after 7 times incorrect try, game over.

I try to put a

while
inside the form's submission, but I don't know how to pause the loop by the next submission.

html:



var resultat = Math.floor(Math.random() * 100) + 1;
$('div').html("( answer is : " + resultat + " )");

$('form').on('submit', function (e){
e.preventDefault();
var inputVal = $('#number').val();
var nbInput = Number(inputVal);

if(nbInput !== resultat){
if (nbInput < resultat) {
$('h2').html(inputVal + ' is too small');
}else{
$('h2').html(inputVal + ' is too big');
};
}else{
$('h2').html('Yes! ' + inputVal + ' is the right number');
};

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Let's Guesse Number</h1>
<form>
<p>Enter the number between 1 and 100</p>
<input id="number" name="number" type="text">
<input type="submit">
</form>
<div></div>
<h2></h2>




Answer

This should do the trick:

var limitCounter = 0;
var resultat = Math.floor(Math.random() * 100) + 1;
$('div').html("( answer is : " + resultat + " )");

$('form').on('submit', function (e){
    if(limitCounter > 7) {
       $('h2').html('You are out of gusses');
       return;
    }

    e.preventDefault();
    var inputVal = $('#number').val();
    var nbInput = Number(inputVal);

    if(nbInput !== resultat){
        if (nbInput < resultat) {
            $('h2').html(inputVal + ' is too small');
        }else{
            $('h2').html(inputVal + ' is too big');	
        };
    }else{
    	$('h2').html('Yes! ' + inputVal + ' is the right number');
    };
    limitCounter++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Let's Guesse Number</h1>
<form>
    <p>Enter the number between 1 and 100</p>
    <input id="number" name="number" type="text">
    <input type="submit">
</form>
<div></div>
<h2></h2>