简体   繁体   中英

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.

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>

You have a problem here:

<input id="tags" name="guess" />

Your id is tags , not guess .

You should use document.getElementById("tags").value .

You are trying to retrieve the value of an element with id of "guess." Change this to "tags."

var info = document.getElementById("tags").value;

Also, as @CodeGodie mentioned, you need to change your function name to something other than submit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM