【问题标题】:Message displayed on form submit disappearing instantly表单提交上显示的消息立即消失
【发布时间】:2012-05-21 17:58:55
【问题描述】:

我为我的 chrome 应用程序创建了一个选项页面。 设计了完美运行的表单,除非现在我尝试添加一条消息(通过 jquery/javascipt),当用户单击保存按钮或重置按钮时。

表单html:

<body onload="loadOptions();">
    <center>
    <div id="wrapper">
    <div id="status">
        <p id="statusMessage"></p>
    </div>
    <form id="settings" align="left" onsubmit="saveOptions(this);">
        <fieldset>
        <legend>General</legend>
          // settings options go here
        </fieldset>
            <center>
            <button type=submit> Save </button>
            <button id="reset" type=reset onclick="reset();"> Restore Defaults </button>
            </center>
    </form>
    </div>
    </center>
</body>

我想在状态消息 div 中显示消息。 所以我写了以下脚本:

function saveOptions(form){


    $("#status").hide();

        //code to save settings

        $("#statusMessage").html("Preferences saved");
        $("#status").show();
    }

    function loadOptions(){         
        //code to load options
    }
    function reset(){
        $("#status").hide();

        //code to reset

        $("#statusMessage").html("Preferences reset to default");
        $("#status").show();
    }

CSS:

div#status{


width: 500px;
    text-align: center;
    background: white;
    border: 3px solid orange;
    border-radius: 5px;
    font-weight: bold;

    display: block;
}
div#status h1,p{
    font-size: 20px;
    text-shadow: 1px 1px 1px lightgrey;
}

问题是消息显示然后div又隐藏了! 我知道这样做的原因是提交表单时页面会刷新,但找不到解决方法。 :(

甚至尝试添加这个

$(function() { $("#status").hide(); });

但没有帮助。

请帮忙!

【问题讨论】:

    标签: javascript jquery html css forms


    【解决方案1】:

    return false 添加到您的表单标记中:

    <form id="settings" align="left" onsubmit="saveOptions(this); return false;">
    

    它会阻止表单被提交。


    另一种方法是使用JQuery submit 事件和preventDefault 方法。

    $("#settings").on("submit", function(e) {
        e.preventDefault();
    
        $("#status").hide();
        $("#statusMessage").html("Preferences saved");
        $("#status").show();
    });
    

    【讨论】:

    • 谢谢伙计。经过一番搜索,发现关于return false。
    • 伙计,如果您能提供帮助,请再做 1 件事。当我单击重置按钮时,将调用 saveOptions 函数,该函数(重新)将消息从“首选项重置为默认值”更改为“已保存首选项”
    • 两个动作都需要一个函数吗?
    • 没有。当用户点击提交时,它应该保存并显示响应消息当用户点击重置为默认时,它应该清除保存的设置并显示响应消息。
    • 已解决...调用 onclick 到提交按钮,只是在表单提交属性中返回 false
    猜你喜欢
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 2015-04-27
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多