2017-08-29 60 views
0

我希望有人能帮助我。双重提交,防止默认不工作

我在我的页面上有两个按钮。 “保存”和“发布”。这是HTML:

<button type="submit" class="button">Save</button> 
<button type="button" class="button" name="publish" value="true" onclick="publishAlbum({{ album.id }}, '{{ album.title }}')">Publish</button> 

第一个保存相册,第二个发送电子邮件给业主。第二个(“发布”)需要先触发确认(“你确定吗?”)。当你点击“确定”时,表单应该提交,但是如果你点击“取消”(在确认框中),它应该什么也不做。

这里是我的JS:

function publishAlbum(album_id, album_title) 
    { 
     var result = confirm('Are you sure you want to publish this album?'); 

     if(!result) 
     { 
      return; 
     } 

    } 

我想所有的一切(防止默认情况下,返回等),但每次我点击“取消”,形式仍然提交和电子邮件发送。

有人可以帮助我吗?

+2

“取消”按钮不是默认的窗体控件。您必须取消提交处理程序中的默认操作,而不是任意点击处理程序。 “ – Teemu

+0

”我尝试了字面上的一切(防止默认“你甚至不传递事件对象到你的点击处理程序你怎么试图防止默认动作呢? –

+0

显示你的代码或它没有发生;) – sandrooco

回答

0

发布

$('.publish-button').on('click',function(e){ 
    e.preventDefault(); 
    let albumId = $('#selectYourAlbumId'); 
    let albumTitle = $('#selectYourAlbumTitle'); 
    var result = confirm('Are you sure you want to publish this album?'); 
    if(!result) 
    { 
     return; 
    } 
    // POST your form through an AJAX call 

}) 
0

你需要得到事件对象以某种方式(例如,通过添加事件监听器按钮)。然后,您可以防止表单提交,就像这样:

const album = { 
 
    id: 1, 
 
    title: 'Test', 
 
}; 
 

 
document.querySelector('[name=publish]').addEventListener('click', function(e) { 
 
    if (!publishAlbum(album.id, album.title)) { 
 
    e.preventDefault(); 
 
    } 
 
}); 
 

 
function publishAlbum(album_id, album_title) { 
 
    var result = confirm('Are you sure you want to publish this album?'); 
 

 
    if (!result) { 
 
    return false; 
 
    } 
 

 
    // do your stuff 
 
    return true; 
 
}
<form action="https://example.org" method="POST"> 
 
    <button type="submit" class="button">Save</button> 
 
    <input type="submit" class="button" name="publish" value="Publish" /> 
 
</form>

0

假设你有一个表单标签内的这些按钮,你可以试试这个:

<html> 
<body> 

<h2>JavaScript Confirm Box</h2> 


<button type="submit" class="button">Save</button> 
<button type="button" class="button" name="publish" value="true" onclick="publishAlbum()" id="myButton">Publish</button> 

<script> 
function publishAlbum() { 
    var txt; 
    if (confirm("Press a button!") == true) { 
     $("#myButton").trigger('submit'); 
    } else { 
     txt = "You pressed Cancel!"; 
     alert(txt) 
    } 
} 
</script> 

</body> 
</html> 
0

我用这个:

$(document).ready(function() { 
    $('#form-publish .button-publish').on("click", function(e) { 
     var c = confirm("Are you sure?"); 
     if (c) { 
      return; 
     } else { 
      e.preventDefault(); 
     } 
    }); 
});