如何防止页面重新加载或刷新取消选项?

时间:2014-03-02 23:35:36

标签: javascript forms submit confirm onsubmit

我正在尝试阻止页面在用户单击“取消”选项时重新加载或提交。我查看了stackoverflow并对我遇到的问题使用了相同的语法,但我尝试了类似的东西,它仍然提交并在取消选项上重新加载页面。如何阻止它执行任何操作并使页面保持原样取消?

JavaScript代码:

// create an input element
var frm = document.getElementById("result");
var submitBtn = document.createElement("input");
submitBtn.type = "submit";
submitBtn.value = "Confirm Purchase";
frm.appendChild(submitBtn);
submitBtn.addEventListener('click', function()
{
    // confirm the data
    var submitQ = confirm('Are you sure you want to submit your DSLR selections?');
    if(submitQ)
    {
    alert('Your query has been submitted! Have a great day! :)');
    }
    else document.getElementById("result").onsubmit = false; // prevent the page from refreshing on Cancel option
});

HTML代码:

<form id="result" onsubmit="true">
    <!--Store User Selection Text Node Element Here-->
        <!--<p>Your DSLR budget range selected was:</p>
    <p>The DSLR brand you selected was:</p>
    <p>The type of photography you selected was:</p>
    <p>The type of lenses you selected was:</p>
    <input type="submit" value="Confirm Purchase"/>
    <input type="button" value="Reset All"/>-->
</form>

2 个答案:

答案 0 :(得分:1)

更改您的事件处理程序以处理表单onsubmit事件,而不是提交按钮click事件。如果用户取消,则返回false:

frm.onsubmit = function(){
    // confirm the data
    var submitQ = confirm('Are you sure you want to submit your DSLR selections?');
    if(submitQ)
    {
    alert('Your query has been submitted! Have a great day! :)');
    } else {
       // prevent the page from refreshing on Cancel option
       return false;
    }
};

看小提琴 - &gt;的 http://jsfiddle.net/LGd2f/

答案 1 :(得分:0)

也许你应该尝试将事件附加到表单提交事件而不是单击按钮,然后只需返回false 返回true