jQuery function not working on Form Submit

2019-07-22 15:19发布

I saw from W3C example something like this. An action happens on form submit(an alert). However, when I tried with my own function here, my action doesn't happen (show hidden div). Goal is to show hidden div on form submit using 'GET' request. I am new to javascript/jQuery/ajax, but isn't jQuery supposed make call to server without refreshing page?

not working javascript:

$(document).ready(function(){
    $("form").submit(function showDiv(){
        document.getElementById("showMe").style.display = "block";
    });
});

not working html:

<body>
    <form action="" method="GET">
    <input type="text" name="LastName" value="Mouse"><br>
    <input type="submit" value="Submit">
    </form> 

    <div id="showMe" style="display: none;">
    <p>hey this should be hidden</p>
    </div>
</body>

4条回答
爷、活的狠高调
2楼-- · 2019-07-22 15:46

Try this:

$("form").submit(function(e){
    e.preventDefault();
    $("#showMe").show();
});
查看更多
等我变得足够好
3楼-- · 2019-07-22 16:02

You need to cancel the form submit before executing your code:

$(document).ready(function(){
    $("form").submit(function(e){
        // At this point you'll want to have some type of flag to indicate whether you
        // should allow the form submission to continue, or cancel the event. For example,
        // it could be whether not showMe is visible (I don't know what you're going for).

        e.preventDefault();
        $("#showMe").css("display", "block");

        // Submit form after your code runs (or whenever you want)
        $("form").submit();
    });
});
查看更多
在下西门庆
4楼-- · 2019-07-22 16:06
$(document).ready(function(){
    $("form").submit(function(e){
        e.preventDefault(); // this will prevent the submit
        document.getElementById("showMe").style.display = "block";
    });
});

Actually the jfiddle you posted is not blocking the form, it shows you an alert that block all js execution (browser behavior), if you select ok in the alert, the form goes through

the event.preventDefault() statement means: don't process anything outside this function

查看更多
smile是对你的礼貌
5楼-- · 2019-07-22 16:06

You need at least one form element (button or input), that has type "submit". Then jQuery .submit() or .on('submit',..) will definitely work.

查看更多
登录 后发表回答