简体   繁体   English

停止按钮提交,然后使用JavaScript提交表单

[英]Stop Button From Submitting Then Submit Form Using JavaScript

I have a delete button that I use globally in many areas of my site. 我有一个删除按钮,可以在网站的许多区域中全局使用。 Here is the code for it. 这是它的代码。

public function delete_button($id_to_be_deleted, $form_to_post_to, $button_name){
    return form_open($form_to_post_to, array('class'=>'table_form spanFormat')) .
    form_hidden(array('id'=>$id_to_be_deleted)) .
    form_submit(array('class'=>'btn btn-sm btn-danger','name'=>$button_name, 'value'=>'Delete', 'onclick'=>'confirmDelete();return false;')) .
    form_close();
}

This piece of code, 'onclick'=>'confirmDelete();return false;' 这段代码'onclick'=>'confirmDelete();return false;' is what should temporarily stop the form from submitting and the run my function here, 是应该暂时阻止表单提交并在此处运行我的功能的东西,

function confirmDelete() {
    var d = confirm("Are you sure you want to delete this?");
    if (d) return true;
    else return false;
}

and if true, then submit the form. 如果为true,则提交表格。

For some reason it opens the popup but does not submit the form after because return false has already fired. 由于某种原因,它会打开弹出窗口,但由于return false已被触发,因此不会提交表单。 But if I remove return false then the form will just submit and never pop open the popup. 但是,如果我删除return false,那么表单将只提交,并且永远不会弹出打开弹出窗口。

Can anybody help me out? 有人可以帮我吗?

Note: I want it done like this if possible. 注意:如果可能,我希望这样做。 I do not want an on form submit, I want my handler from the button. 我不希望提交表单,我希望我的处理程序从按钮开始。 This is because my delete forms all have different names but my buttons should all pop up this confirm dialog. 这是因为我的删除表单都具有不同的名称,但是我的按钮都应该弹出此确认对话框。

Onclick is the wrong event to use. Onclick是使用错误的事件。 You want to hook the submit event, so let´s start with 您想钩住Submit事件,所以从

<input type='submit' onclick="

Then you want to actually use the result of the confirmation, so return it directly: 然后,您想实际使用确认结果,因此直接将其返回:

<input type='submit' onclick="return confirm('sure?')"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM