简体   繁体   中英

Why won't my return work?

I only just started learning JS like 5-10 minutes ago, I was told by someone to try and create a basic validation feature, however it doesn't seem to work as wanted. It checks if field is empty, that part works. But checking if it's got something in it and carrying on running the code doesn't.

my form:

echo '<form action="index.php?action=getHashedText" method="post"     name="formHash">
        <br/><textarea name="text" rows="4" cols="50" placeholder="Add your text/pharse/word which you want hashing here." autofocus></textarea><br/>
        <button type="button" name="button" onclick="return validate();">Hash</button>';

function validate():

    <script>
    function validate() {
        with (window.document.formHash) {
            if (formHash.text.value === "") {
                    alert('Field is empty!');   
                    return false;
            } else {
                    return true;
            }    
        }  
    }
    </script>

The problem is you are using a button that is not submitting the form anyway (regardless of your js), change this dom:

<button type="button" name="button" onclick="return validate();">Hash</button>

To this: Fiddle

<input type="submit" name="button" value="Hash" onclick="return validate();" />

Or you can just add type="submit" on your <button> (HT @RocketHazmat): Fiddle

<button type="submit" name="button" onclick="return validate();">Hash</button>

Or you can just remove the type on your <button> all together as the default type is submit (HT @FabrícioMatté): Fiddle

<button name="button" onclick="return validate();">Hash</button>

Also, slightly off topic but I would get in the habit of avoiding putting javascript onclicks directly on your elements. You can create listeners instead: addEventListener

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