I'm trying to get my form to not submit when I press the cancel button on my JavaScript dialog.
I have this code:
$(document).ready(function() {
$("#submit").click(function (e) {
e.preventDefault();
var link = $(this).attr("href"); // "get" the intended link in a var
var result = confirm("Are you sure you want to log this fault?");
if (result) {
document.location.href = link; // if result, "set" the document location
}
});
});
The form submits regardless if I press the Ok or Cancel buttons or not even though I have the prevent default code.
My HTML code is:
<button type="submit" id="submit" class="btn btn-default"><span class="glyphicon glyphicon-floppy-save"></span></button>
<form id="myform" method="post" action="/the/post/url">
<!-- other elements -->
....
....
....
<button type="submit" id="submit" class="btn btn-default">
<span class="glyphicon glyphicon-floppy-save"></span>
</button>
</form>
$(function() {
//this would do the same as button click as both submit the form
$(document).on("submit", "#myform", function (e) {
var result = confirm("Are you sure you want to log this fault?");
//if cancel is cliked
if (!result) {
return false;
}
//if ok is cliked, form will be submitted
});
});
the following like won't work since this reffers to the submit button which does not have an href attribute.
var link = $(this).attr("href"); // is invalid.
try
$(document).ready(function() {
$("#submit").click(function (e) {
e.preventDefault();
var result = confirm("Are you sure you want to log this fault?");
if (result) {
$('#formId').submit(); // where formId is the id of your form
document.location.href = "url to which you want to redirect";
}
else
return false;
});
});
side note: from wherever you got this piece of code, they must be using a hyperlink <a> styled like a button, with a valid href attribute :)
Related
I hope someone can help me.
I have two buttons on my page in my form. "Save" and "Publish". This is the 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>
The first one saves the album, the second one sends an e-mail to the owner. The second one ("Publish") needs to trigger a confirm first ("Are you sure?"). When you click "Ok", the form should submit, but if you click "Cancel" (in the confirm box), it should do nothing.
Here is my JS:
function publishAlbum(album_id, album_title)
{
var result = confirm('Are you sure you want to publish this album?');
if(!result)
{
return;
}
}
I tried literally everything (prevent default, return etc), but every time I click "Cancel", the form still submits and the e-mail is sent.
Can someone help me?
Publish
$('.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
})
You need to get the event object somehow (e.g. by adding an event listener to the button). Then you are able to prevent the form submission, like so:
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>
Assuming you have these buttons inside a form tag, you can try this:
<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>
I used this:
$(document).ready(function() {
$('#form-publish .button-publish').on("click", function(e) {
var c = confirm("Are you sure?");
if (c) {
return;
} else {
e.preventDefault();
}
});
});
I have a form with a submit and cancel button and I want to show a different confirm message bepending on which button is clicked so this is what I've come up with.
function confirmDialog(buttonId) {
switch (buttonId) {
case "cancel":
var result = confirm("cancel message");
submitForm(result);
break;
case "submit":
var result = confirm("Submit message");
submitForm(result);
break;
}
};
And my submitForm function looks like
function submitForm(result) {
console.log(result); //this is false when I click cancel in the confirm box
if (result && $("#myform").valid()) {
$("#myform").submit();
}
else {
return false;
}
};
Now my issue is that when I click cancel the form still gets submited. Can someone tell me what I'm doing wrong please. I have return false; in my else condition so I really don't know why it still submits the forms.
I've looked at the following questions but I'm still facing the issue
jQuery Still Submits Ajax Post Even When “Cancel” is clicked on Confirm Dialog
javascript confirm (cancel) still submits form when returning false
Edit: Cancel button html as requested
<button type="submit" id="cancel" class="btn btn-danger btn-block" value="Cancel">Cancel</button>
Further Edit
I call the confirmDialog function in the click event the appropriate button as follows:
$("#cancel").click(function () {
var buttonId = $(this).attr("id");
confirmDialog(buttonId)
});
your button have default behavior of submit
replace
<button type="submit" id="cancel" class="btn btn-danger btn-block" value="Cancel">Cancel</button>
with
<button id="cancel" class="btn btn-danger btn-block" value="Cancel">Cancel</button>
... Edit after your update Try this code ....
replace your code
function submitForm(result) {
console.log(result); //this is false when I click cancel in the confirm box
if (result && $("#myform").valid()) {
$("#myform").submit();
}
else {
return false;
}
};
with
function submitForm(result) {
console.log(result); //this is false when I click cancel in the confirm box
if (result && $("#myform").valid()) {
$("#myform").submit();
}
else {
const element = document.querySelector('myform');
element.addEventListener('submit', event => {
event.preventDefault();
console.log('Form submission cancelled.');
});
}
};
----- Alternative working code if you consider changing your HTML structure ---
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
</head>
<body>
<form id="MyForm">
<button id="btnSubmit" class="btn btn-primary">Submit</button>
<button id="btnCancel" class="btn btn-danger">Cancel</button>
</form>
<script type="text/javascript">
$(function () {
$("#btnSubmit").click(function (e) {
e.preventDefault();
$('#MyForm').submit();
});
$("#btnCancel").click(function (e) {
e.preventDefault();
var result = confirm("Sure Cancel?");
if (result) {
const element = document.querySelector('#MyForm');
element.addEventListener('submit', function (e) {
e.preventDefault();
});
alert("Form Submission Canceled");
}
else {
$("#MyForm").submit();
alert("Form Submitted");
}
});
})
</script>
</body>
</html>
Your <button> tag's type attribute seems to have submit as its value, just remove the type="submit" attribute in your HTML code and keep it just <button id="cancel".... />
<button id="cancel" class="btn btn-danger btn-block" value="Cancel">Cancel</button>
This will resolve your issue. Hope this helps!
The form submit is only omitted when "onsubmit" gets "false" from the Javascript handler.
Try this
"return submitForm..." (instead of just "submitForm...")
(2. Remove semicolons after function's closing brackets)
Update
Maybe the problem is the combination of input type=submit and $("#myform").submit();
If <form onsubmit=... receives no false (for example from a function return), the form will be submitted.
If <input type=submit onclick=... receives no false (for example from a function return), the button action (form submission) will be performed.
Raw (unchecked) solution option without using input type=submit:
HTML
<form id="myform" onsubmit="formValidation()">
<button value="Submit" onclick="buttonHandler(true)">
<button value="Cancel" onclick="buttonHandler(false)">
</form>
JS
function formValidation()
{
return $("#myform").valid();
}
function buttonHandler(isSubmit)
{
if (isSubmit ==== true)
{
if (confirm(submitMessage) === true)
{
$("#myform").submit();
}
}
else
{
if (confirm(cancelMessage) === true)
{
$("#myform").submit();
}
}
}
You can get this to work if you use an input tag instead of button tag and retain your styles by keeping your classes. e.g.
<input id="SomeId"
class="btn btn-danger btn-block"
onclick="return confirm('Are you sure you want to delete: X');"
value="Delete" />
I had similar problem and solved it with click event, which is very similar to your problem.
Try this:
$("#cancel").click(function () {
var buttonId = $(this).attr("id");
confirmDialog(buttonId);
return false;
});
Hope it helps.
Your tag's type attribute seems to have submit as its value, just remove the type="submit" attribute in your HTML code and keep it just
<button id="cancel".... />
I have a simple form with two inputs: "title" and _"description", and two buttons: "save" (save for later) and "submit". For both I would want to get the values of my form fields and insert/update my collections accordingly.
<template name="NewScenarioForm">
<form id="newScenarioForm" >
<textarea type="text" id="title" name="title" rows="1" cols="75" placeholder="Type to add a title"></textarea><br/>
<textarea type="text" id="description" name="description" rows="4" cols="100" placeholder="Type to add a description" ></textarea><br/>
<input type="submit" id="saveScenarioButton" name="action" title="Save Scenario" value="Save" />
<input type="submit" id="submitScenarioButton" name="action" title="Submit for approval" value="Submit" />
</form>
</template>
Right now I'm detecting the event like this:
"click #saveScenarioButton": function(event, template) {
event.preventDefault();
var title = template.find("#title").value;
var description = template.find("#description").value;
...
//Do stuff with this information to persist information
Meteor.call("saveScenario", title, description);
....
}
And I need to repeat the whole function for the other button. I would would like to detect the event and determine which button was pressed instead.
I have been struggling with an event handler like:
"submit #newScenarioForm": function(event) {
But then I don't know how to determine the button clicked, since I can't figure out an event property. Is there a way to determine the button if I wanted to use the form ID in my event handler instead of the ID of each button (or a smarter way to approach this altogether?)?
You could make the event target inputs with type submit:
Template.NewScenarioForm.events({
"click input[type=submit]": function(e) {
if ($(e.target).prop("id") == "saveScenarioButton") {
// Save the scenario
} else if ($(e.target).prop("id") == "submitScenarioButton") {
// Submit the scenario
}
}
});
You could also make it check the clicked button's value, and drop the ID field
Please note that this will not handle other ways of submitting the form, for example the user pressing Enter in an input field. An approach to handle this as well could be to define a few functions:
function scrapeForm() {
// Collects data from the form into an object
}
function saveData() {
var formData = scrapeForm();
// More logic to save the data
}
function submitData() {
var formData = scrapeForm();
// More logic to submit the data
}
Template.NewScenarioForm.events({
"click input[type=submit]": function(e) {
if ($(e.target).prop("id") == "saveScenarioButton") {
saveData();
} else if ($(e.target).prop("id") == "submitScenarioButton") {
submitData();
}
},
"submit #NewScenarioForm":
// Default action on submit.
// Either save the data
saveData
// or submit the data
submitData
// or nothing, requiring the user to actually click one of the buttons
function(e) {e.preventDefault();}
});
Why not just give them both the same class like submitForm
<input class="submitForm"** type="submit" id="saveScenarioButton" name="action" title="Save Scenario" value="Save" />
<input class="submitForm" type="submit" id="submitScenarioButton" name="action" title="Submit for approval" value="Submit" />
then have a onClick for .submitForm like so:
$('.submitForm').on('click', function () {...});
and inside the function get id by doing:
var id = $(this).attr('id');
full code:
$('.submitForm').on('click', function () {
var id = $(this).attr('id');
... the rest of your code ...
});
I do this to correctly identify buttons using class or id.
helloWorld.html
<head>
<title>helloWorld</title>
</head>
<body>
<h1>Welcome to Meteor!</h1>
{{> hello}}
</body>
<template name="hello">
<button class="plus5">+5</button>
<button class="minu5">-5</button>
<button id="plus1">+1</button>
<button id="minu1">-1</button>
<p>You've pressed the button {{counter}} times.</p>
</template>
helloWorld.js
if (Meteor.isClient) {
// counter starts at 0
Session.setDefault('counter', 0);
Template.hello.helpers({
counter: function () {
return Session.get('counter');
}
});
Template.hello.events({
'click button.plus5': function () {
Session.set('counter', Session.get('counter') + 5);
},
'click button.minu5': function () {
Session.set('counter', Session.get('counter') - 5);
},
'click button#plus1': function () {
Session.set('counter', Session.get('counter') + 1);
},
'click button#minu1': function () {
Session.set('counter', Session.get('counter') - 1);
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
}
click .plus5, click #plus1 also work.
I have simple HTML code
<form class="searchbox" action="" >
<input type="search" placeholder="Search KB" id="SearchField"/>
<button value="search" id="SearchButton"> </button>
</form>
and simple event listener
$('#SearchButton').on("click",function(events) {
// your stuff
alert("work darn it!!!!!!!!!!!!!!!!!!!!!!!!!")
events.preventDefault();
var bla = $('#SearchField').val();
console.log("bla")
var jsonString = JSON.stringify(bla);
return false;
});
when i click button page keeps refreshing
when i put this
It doenst run my event listener when i do this
I am not getting where i am going wrong
Update your Jquery like this -
$(document).ready(function(){
$('#SearchButton').click(function() {
alert('working fine..');
return false;
});
});
Update like below,
$(function(){
$('#SearchButton').click(function() {
alert('working fine..');
var bla = $('#SearchField').val();
alert('Search field name :'+bla);
return false;
});
This should work now. You've to just disable the default function that submit button in a form has that is to self post.
$('#SearchButton').on("click",function(e) {
// Stop propagation & prevent Default action
e.stopPropagation();
e.preventDefault():
alert("work darn it!!!!!!!!!!!!!!!!!!!!!!!!!")
var bla = $('#SearchField').val();
console.log("bla")
var jsonString = JSON.stringify(bla);
return false;
});
Im using the following button which is working fine and invoke the action as expected,
save button
#using (Html.BeginForm("edit", "user", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" id="actionbtn" value="Save" name="buttonType" />
</div>
</div>
}
Check button
#using (Html.BeginForm("Check", "User"))
{
<input type="submit" id="btnConnect" value="Check" />
<span id='result'></span>
}
now when I add the following code that should add some text if the operation was successful or not ,the save button does not invoke the action ,what am I doing wrong here?
$("form").submit(function (e) {
// Cancel the default submission
e.preventDefault();
// Perform the AJAX call
var target = $(this).attr('action');
$.post(target, function(result) {
// Check the value of result
if (result === "True") {
// It was successful, make result text green.
$("#result").css('color', 'green').html("successful.");
} else {
// Otherwise, it failed, display as red.
$("#result").css('color', 'red').html("Failed");
}
});
});
i've try to remove e.preventDefault(); without sucess...
you need to check like this that form submitted via which button.
you have to do like this to restrict it:
$("form").submit(function (e) {
// Cancel the default submission
e.preventDefault();
if($(this).find('input[type="submit"]').val() === "Check") // form submitted via Check button
{
// Perform the AJAX call
var target = $(this).attr('action');
$.post(target, function(result) {
// Check the value of result
if (result === "True") {
// It was successful, make result text green.
$("#result").css('color', 'green').html("successful.");
} else {
// Otherwise, it failed, display as red.
$("#result").css('color', 'red').html("Failed");
}
});
}
else
{
// form submitted from Save button
}
});
First of all you need to add ID to your form:
#using (Html.BeginForm("Check", "User",FormMethod.Post, new { Id = "CheckForm" })
Then you need to add submit event handler only to form that needed:
$("#CheckForm").submit(function (e) {
// Cancel the default submission
e.preventDefault();
// Perform the AJAX call
var target = $(this).attr('action');
$.post(target, function(result) {
// Check the value of result
if (result === "True") {
// It was successful, make result text green.
$("#result").css('color', 'green').html("Successful.");
} else {
// Otherwise, it failed, display as red.
$("#result").css('color', 'red').html("Failed");
}
});
});
There is also another thing. When you make Ajax submit like this - then it will make submit of empty form. Is what you need?