Jquery form not saved - javascript

If a user tries to leave a page without saving it they get a message telling them.
But they also get it if they have saved the form too.
$("#locForm").change(function () {
mod = 1;
});
window.onbeforeunload = function confirmExit() {
if (mod == 1) {
return "information not saved.";
}
}
$("input[name='commit']").click(function () {
mod = 0;
});
This is my save button:
<button type="submit" class="btn btn-sample btn-md reset" id="send" name="commit"><b>Save</b></button>
How can it only warn user if they haven't saved the form?

You're using the wrong selector. Use:
$("button[name='commit']")

Related

How to send confirm "ok" / ""cancel" from JS to Flask

I am trying to find a means to "collect" the input from the user, say if the user presses "OK" in a JS confirm window, I want to receive a "True" in python's flask, and "False" if users presses "Cancel".
I have this part for the JS function:
<script>
function confirmBooking(elem) {
if(confirm('Are you sure you want to book this slot?') == true) {
//elem = 1;
alert("its done: " + elem);
}
else {
return 0;
}
}
</script>
Now on "form" side I have this:
<form method="post">
<button type="submit" name="free_button" value="free_button" onClick="confirmBooking('{{ booking_slot }}')"> Free </button>
</form>
So, here, booking_slot is a python variable containing some string. I would like some means to set a True/False value to a variable in the Flask side if the user selects "OK" or "cancel" respectively.
Any way to achieve this? Thanks.
You need to create a function that will collect or fetch the input from your frontend to the backend. I usually do this technique.
<form action="{{url_for('/collect')}}" method="post">
<input type="hidden" id="userInput" name="userInput">
<button type="submit" name="free_button" value="free_button" onClick="confirmBooking('{{ booking_slot }}')"> Free </button>
</form>
<script>
function confirmBooking(elem) {
if(confirm('Are you sure you want to book this slot?') == true) {
//elem = 1;
alert("its done: " + elem);
document.getElementById("userInput").value = "True";
}
else {
document.getElementById("userInput").value = "False";
return 0;
}
}
</script>
#app.route('/collect',methods=["POST"])
def collect():
if request.method =="POST":
userInput = request.form.get("userInput")
return render_template('<template here>',userInput=userInput)

How to create dynamic functionality using Javascript and HTML?

I'm creating a page which has multiple order buttons (One for each menu item). When an order is placed I want to call a Javascript function to change only the order button pressed rather than every button with the ID. There has to be better implementation for these function calls... Anyone?
function orderFood1(helpVal) {
if (document.getElementById("food1").innerHTML === "Order") {
document.getElementById("food1").innerHTML = "✅";
// Alert waiter
} else {
document.getElementById("food1").innerHTML = "Order";
// Cancel Request
}
}
function orderFood2(helpVal) {
if (document.getElementById("food2").innerHTML === "Order") {
document.getElementById("food2").innerHTML = "✅";
// Alert waiter
} else {
document.getElementById("food2").innerHTML = "Order";
// Cancel Request
}
}
function orderFood3(helpVal) {
if (document.getElementById("food3").innerHTML === "Order") {
document.getElementById("food3").innerHTML = "✅";
// Alert waiter
} else {
document.getElementById("food3").innerHTML = "Order";
// Cancel Request
}
}
<button type="button" id="food1" onclick="orderFood1()" class="btn btn-primary">Order</button>
<button type="button" id="food2" onclick="orderFood2()" class="btn btn-primary">Order</button>
<button type="button" id="food3" onclick="orderFood3()" class="btn btn-primary">Order</button>
They all look to do nearly the same thing, so you can use only a single function. To identify which button was clicked, you can examine the clicked button from the listener - the target of the event. Also, best to avoid inline handlers - attach the listeners properly using Javascript instead.
Since you're only inserting text, it'd be more appropriate to retrieve and assign to the textContent of the element, rather than its innerHTML.
const handleOrder = ({ target }) => {
if (target.textContent === 'Order') {
target.textContent = '✅';
console.log('Alerting waiter');
} else {
target.textContent = "Order";
console.log('Canceling request');
}
};
for (const button of document.querySelectorAll('button')) {
button.addEventListener('click', handleOrder);
}
<button type="button" class="btn btn-primary">Order</button>
<button type="button" class="btn btn-primary">Order</button>
<button type="button" class="btn btn-primary">Order</button>
I think you can create the following html code:
<button type="button" id="food1" onclick="orderFood('food1')" class="btn btn-primary">Order</button>
<button type="button" id="food2" onclick="orderFood('food2')" class="btn btn-primary">Order</button>
Which means that you use only single orderFood function, that gets the ID of the button element as a parameter.
And then your JS code could be something like this:
function orderFood(foodId) {
if (document.getElementById(foodId).innerHTML === "Order") {
document.getElementById(foodId).innerHTML = "✅";
// Alert waiter
} else {
document.getElementById(foodId).innerHTML = "Order";
// Cancel Request
}
}

Double submit, prevent default not working

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();
}
});
});

Cancel on confirm still submits form

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".... />

JavaScript Prevent Form Submit

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 :)

Categories