jQuery - Cancel form submit (using “return false”?)?

后端 未结 12 1599
盖世英雄少女心
盖世英雄少女心 2020-12-19 04:00

I\'m running into a bit of trouble while trying to cancel the submit of a form. I\'ve been following this tutorial (even though i\'m not making a login script), and it seems

相关标签:
12条回答
  • 2020-12-19 04:24

    You have to do a sort of 'double return', or in other words, you have to return what is returned. So, you have your html:

    <form action="index.php" onsubmit="return cancelSubmit()" method="post" name="pForm">
        <textarea name="comment" onclick="if(this.value == 'skriv här...') this.value='';" onblur="if(this.value.length == 0) this.value='skriv här...';">skriv här...</textarea>
        <input class="submit" type="submit" value="Publicera!" name="submit" />
    </form>
    

    Than you just have a jquery function that is called onsubmit as you see above:

    function cancelSubmit() {
        return false; // return true if you want submission to carry through
    }
    

    You can put any sort of conditionals in the function above. It seems you simply want to cancel it though. Hope this helps for others that come across this answer.

    0 讨论(0)
  • 2020-12-19 04:27

    The form you're trying to access might be dynamically added to your page. You need to use delegate to access that form in that case

    Example:

        $(document).delegate("#myform","submit",function(){
           return false;
    });
    
    0 讨论(0)
  • 2020-12-19 04:35

    I had this same problem and it was down to using Rails and :remote => true on the form. Rails jQuery driver was coming in and submitting the form by ajax while my own function was trying to stall the submission process using return false and event.preventDefault().

    So look out for frameworks and default actions that interfere with your own javascript. return false should work :)

    0 讨论(0)
  • 2020-12-19 04:36

    The value of name needs quotes around it. Try this:

    $(document).ready(function() {
        $("form[name='pForm']").submit(function(){
            return false;
        });
    });
    
    0 讨论(0)
  • 2020-12-19 04:36

    How about this one?

    $('form[name=pForm]').on('submit',function()
    {
        console.log("(^o^)");
        return false;
    });
    
    0 讨论(0)
  • 2020-12-19 04:38

    Thanks for the respond everybody! A friend of mine tipsed me to add

    onsubmit="return(false)
    

    on the form. That works, but i'd still like to know a not-inline-javascript trick that works.

    0 讨论(0)
提交回复
热议问题