JS确认并且提交不起作用

时间:2014-05-02 14:15:36

标签: javascript html

这是我的JS:

function confirmPurchase(){
    var answer = confirm('Are you sure you want to purchase the ticket?');
    return answer;
}

function init(){
    purchaseForm.onsubmit = confirmPurchase;    
}

但是当我点击"取消"在alertbox上,它仍在提交表单。如何停止提交表格"取消"并且只允许在" OK"点击了吗?

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

var form = document.getElementById('myForm'),
    confirmPurchasePrompt = function(e) {
        var answer = confirm('Are you sure you want to purchase the ticket?');

        if (!answer) {
            e.preventDefault();
        }
    };


form.addEventListener('submit', confirmPurchasePrompt, true);

在这里演示:http://jsfiddle.net/Uf8Y3/

请注意,这仅适用于现代浏览器(IE> 8),但这是一般的想法。我确定你可以通过一些研究使它与旧版本兼容。

实际上,这可能会有所帮助:
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener#Older_way_to_register_event_listeners

或者这个:
http://css-tricks.com/snippets/javascript/addeventlistner-polyfill/

前夕这个:
https://gist.github.com/eirikbacker/2864711

答案 1 :(得分:0)

首先是表格

<form action="/" id="myform">
    <input type="submit">
</form>

然后JS:

function confirmPurchase(){
    var answer = confirm('Are you sure you want to purchase the ticket?');
    return answer;
}

function init(){
    var purchaseForm = document.getElementById('myform');
    purchaseForm.onsubmit = confirmPurchase;    
}

init();

工作演示:http://jsfiddle.net/TEKRL/