If the textbox has the correct value, onclick button, message on the same page, if not message alert

StackOverflow https://stackoverflow.com/questions/22850865

  •  27-06-2023
  •  | 
  •  

Question

I want to create for my daughters a kind of multiplication quiz web page in which they just have to type a number in a textbox, then click a button. If the number in the textbox is the correct answer I want the page to show a message that says: CORRECT! The message in the web page is not a problem, I can handle but what I'm looking for that I haven't found it is that I want them to type the number that is suppost to be there. For example:

(This [__] simulates a textbox)
(This ██ simulates a button)

I wrote: 2 x 2 = [__] ██

In the above example, they must type "4" (without the quotes) in the textbox and when press the button (the button value is: CHECK ANSWER) then above of the math exercise says: CORRECT! If they type other number that is not "4" (without the quotes) I want a message alert saying: INCORRECT!

I want to apply that for all Table 2 like this:

2 x 2 = [__] ██

2 x 3 = [__] ██

2 x 4 = [__] ██

And to all the Tables 3, 4, 5, 6, 7, 8, 9 10, 11, 12.

I want every button to interact to its corresponding textbox. Thanks. :-)

Was it helpful?

Solution

Here's what you've asked:

$(document).ready(function() {

    var START_TABLE = 1;
    var END_TABLE = 9;
    var START_MULTIPLIER = 1;
    var END_MULTIPLIER = 9;

    var $quiz = $('#quiz');
    var html = [];

    for (var i = START_TABLE; i <= END_TABLE; i++) {
        html.push('<div class="block">');
        for (var j = START_MULTIPLIER; j <= END_MULTIPLIER; j++) {
            html.push(
                '<p>' +
                    '<span class="i">' + i + '</span>' +
                    ' x ' +
                    '<span class="j">' + j + '</span>' +
                    ' = ' +
                    '<input type="text" class="res">' +
                    '<button class="check">Check!</button>' +
                '</p>'
            );
        }
        html.push('</div>');
    }
    $quiz.html(html.join(''));

    $quiz.on('click', 'button.check', function() {
        var $p = $(this).parent('p');
        var res = parseInt($p.find('.res').val());
        var i = +$p.find('.i').text();
        var j = +$p.find('.j').text();

        if (res == i * j) {
            alert('Correct!');
        } else {
            alert('Incorrect!');
        }
    });
});


And in your <body>:

<div id="quiz">
</div>


Working demo: http://jsfiddle.net/Cp8rY/1/

I've used jQuery so don't forget to include it on your web page (or modify the code to not use it).

But, please, in the future don't ask others to write all the code at your place: https://stackoverflow.com/help/on-topic

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top