I'm trying to add adelay on my submit button in javascript.
But it just seems to freeze and no longer commits any action after clicking on it.
Does anyone have an explanation ?
function Progress() {
var button = document.getElementById("Button");
var form = document.getElementById("new_video")
form.onsubmit = function() {
return false;
}
button.onclick = function() {
setTimeout(function() {
form.submit();
}, 2000);
return false;
}
}
<input type="submit" name="commit" value="Upload" class="btn btn btn-primary" onclick="Progress()" id="Button" data-disable-with="Upload" disabled="">
// Cache your Form Elements
const EL_form = document.querySelector("#myForm");
const EL_formSubmitBtn = EL_form.querySelector("#Button");
const Progress = (evt) => {
evt.preventDefault(); // Prevent Browser Submit action
EL_formSubmitBtn.disabled = true; // Disable the submit button
setTimeout(function() {
EL_form.submit(); // Or do AJAX stuff here
EL_formSubmitBtn.disabled = false; // Enable the submit button
}, 2000);
};
// Use Element.addEventListener instead of inline JS
// Don't attach handlers to button, rather use the Form "submit" Event:
EL_form.addEventListener("submit", Progress);
<form id="myForm" action="demo.php">
<input id="Button" type="submit" value="Upload" class="btn btn btn-primary">
</form>
PS: Don't capitalise names of regular functions that do not actually return an Object - or are not a Class by definition, use rather progress as your function name. Or rather be more descriptive, it's actually a formSubmitHandler
You could try this:
var button = document.getElementById("Button");
var form = document.getElementById("new_video");
button.onclick = function(event) {
event.preventDefault();
setTimeout(form.submit, 2000);
}
and
<input type="submit" name="commit" value="Upload" class="btn btn btn-primary" id="Button" data-disable-with="Upload">
Hope this helps.
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".... />
To make it clearer.
JavaScript.
I need to replicate the behaviour of a confirm() but without using a confirm() xd.
So basically, i have to stop the submit and wait for a true/false value from the user and the submit the form.
Now i´m preventing the form submit and then when the user click "yes" force the submit again with a .submit().
But i don´t know if is there any way to keep the on submit event waiting for a true or false return from another function.
Thank you.
Edit: I´ve just realized i can´t do a .submit() cause it will launch the onsubmit even again.
With confirm():
document.getElementById('submit-button').onclick = function() {
if(confirm('Are you sure you want to submit?')) {
// Do something
}
// Don't do something
}
<body>
<input type="text" name="input" />
<button id="submit-button" type="submit">Submit</button>
</body>
Without confirm():
var submit = document.getElementById('submit-button');
var confirm = document.getElementById('confirm-button');
var cancel = document.getElementById('cancel-button');
document.getElementById('submit-button').onclick = function() {
submit.style.display = 'none';
confirm.style.display = 'inline';
cancel.style.display = 'inline';
}
document.getElementById('confirm-button').onclick = function() {
// Submit form
}
document.getElementById('cancel-button').onclick = function() {
submit.style.display = 'inline';
confirm.style.display = 'none';
cancel.style.display = 'none';
}
<body>
<input type="text" name="input" />
<button id="submit-button" type="submit">Submit</button>
<button id="confirm-button" type="submit" style="display: none;">Confirm</button>
<button id="cancel-button" type="submit" style="display: none;">Cancel</button>
</body>
I have a form with multiple buttons that submit to it that differ by value. After I click a button, and then click a second button, the function operates on them both instead of just the second button. Is there a way to prevent this behavior?
This is somewhat related to a question I asked here: Why does function only work on second click? but the solution isn't valid if there a multiple buttons as it just registers the first button from the list of buttons.
JS:
$(document).ready(function () {
$(':button').click(function (){
var myval = $(this).attr("value");
$('#post-form').on('submit', function(event) {
event.preventDefault();
console.log("form submitted!");
console.log(myval);
//var cbtn = $("button");
//var btnval = cbtn.val();
//console.log(cbtn);
document.getElementById('gbimg').style.display = 'none';
document.getElementById('rgimg').style.display = 'none';
create_post(myval);
});
});
function create_post(btnval) {
console.log("create post is working!");
$.ajax({
HTML:
<form action="/create_post/" method="POST" id="post-form">
<div class="col-sm-4" id="toprow">
<h4 style="font-family:verdana"> Models </h4>
<img src='{% static 'images/USAcomplete2.png' %}' class="img-responsive thumbnail" id='gbimg' >
<div class="btn-toolbar">
<button type="submit" name="model" value="test" class="btn btn-default">test</button>
<button type="submit" name="model" value="test2" class="btn btn-default">test2</button>
<button type="submit" name="model" value="test3" class="btn btn-default">test3</button>
</div>
</div>
</form>
You need to prevent the form from submitting before the user clicks the button.
$(document).ready(function () {
$('#post-form').on('submit', function(event, myval) {
event.preventDefault();
console.log("form submitted!");
console.log(myval);
//var cbtn = $("button");
//var btnval = cbtn.val();
//console.log(cbtn);
document.getElementById('gbimg').style.display = 'none';
document.getElementById('rgimg').style.display = 'none';
create_post(myval);
});
$(':button').click(function (){
var myval = $(this).attr("value");
$('#post-form').trigger('submit', myval);
});
Update
Sorry, I think this code should work. The above code would run twice, since a button click would be considered a form submit as well.
$(document).ready(function () {
$('#post-form').on('submit', function(event) {
event.preventDefault();
});
$(':button').click(function (){
var myval = $(this).attr("value");
console.log("form submitted!");
console.log(myval);
//var cbtn = $("button");
//var btnval = cbtn.val();
//console.log(cbtn);
document.getElementById('gbimg').style.display = 'none';
document.getElementById('rgimg').style.display = 'none';
create_post(myval);
});
What is happening here is that you are binding the submit event to #post-form a second time when a second button is clicked, as the binding happens inside the button clicking event callback.
The best way to prevent this is to move this
$('#post-form').on('submit', function(event) {
...
});
outside of your button click event.
I use the following code for edit operation and I've button in the edit screen which I want that it will be enabled when the edit is success
how can I do that?
This is the edit operation
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="UserId,FirstName,LastName,Email,Phone,PhoneWork,WorkingAt")] User user)
{
if (ModelState.IsValid)
{
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
}
return View(user);
}
This is the button
#using (Html.BeginForm("check", "User"))
{
<input type="submit" id="btn" value="check" />
<span id='result'></span>
}
First You have to disable your button on load
#using (Html.BeginForm("check", "User"))
{
<input type="submit" id="btn" value="check" disabled />
<span id='result'></span>
}
and on your edit button write function onclick=enable(); add jquery
<script type="text/javascript">
function enable() {
var btn = document.getElementById("btn");
btn.disabled = false;
}
</script>
Just make sure your use button tag with type submit
<button type="submit" id="btn" value="check">Save</button>
This is what i m doing for my buttons, just use javascript to achieve.
<script>
$(document).ready(function () {
$(document).on('invalid-form.validate', 'form', function () {
var button = $(this).find('button[type="submit"]');
setTimeout(function () {
button.removeAttr('disabled');
}, 1);
});
$(document).on('submit', 'form', function () {
var button = $(this).find('button[type="submit"]');
setTimeout(function () {
button.attr('disabled', 'disabled');
}, 0);
});
});
</script>
Let me know if that helps.