Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML text input conditional submit

I have a page that loads a random MP3 file on each refresh. The user has to guess a name based on the sound via text form input. I want to check their input against the stored string and refresh the page if it's correct. Otherwise, I wan't to give them an incorrect alert and stay on the same page so they can guess again:

<div class="ui-widget" align="center">
<form method="post" action="" class="answer_box" onsubmit="return submit();">
    <p>Which hero is it?  <input id="tags" name="guess"  /></p>
    <script>
        var key = <?php echo json_encode($rand_key) ?>;
        var info = document.getElementById("guess").value;

        function submit() {
            if (key==info){
                alert('Correct!');
                return true;
            }
            else {
                alert('Incorrect!');
                returnToPreviousPage();
                return false;
            }
        }
    </script>

</form>
</div>

Right now, it submits the information to a new page regardless of the input. The javascript alerts are also not showing (I suspect they do show, but the page then refreshes and they disappear). The key variable is the key from the randomly taken value of a PHP array, and info should be the text the user inputs.

like image 823
Mason Avatar asked Dec 25 '22 14:12

Mason


1 Answers

Problems found:

  1. you cant use submit as a function name a this is an HtmlForm object
  2. document.getElementById("guess").value; is looking for an element with ID of "guess" and that does not exist.

I would rewrite your script like this:

<script>
    var key = <?php echo json_encode($rand_key) ?>;

    function my_submit(curr) {
        var info = curr.guess.value;
        if (key == info) {
            alert('Correct!');
            return true;
        }
        else {
            alert('Incorrect!');
            returnToPreviousPage();
            return false;
        }
    }
</script>

<form onsubmit="return my_submit(this);">
    <p>Which hero is it? <input id="tags" name="guess"/></p>
</form>
like image 58
CodeGodie Avatar answered Dec 27 '22 04:12

CodeGodie