enable button when the save finish successful - javascript

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.

Related

Delay Button Submit Javascript

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.

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

Two button click events in Jquery

HTML
<input type="Submit" value="Add" id="btn1"/>
<input type="Submit" value="Add2" id="btn2"/>
Jquery
$("#btn1").click(function () {
$("[id*=btn2]").click();
});
Controller
[httpPost]
Public ActionResult MyAction(){
//some code
return view();
}
Here, how can I differentiate, whether I have directly clicked the btn2 or it is coming from btn1?
Keep an hidden html tag for keeping track.
Here, get the value from #ViewBag.hdnIsButton1Clicked for [HtpGet]/initial request for the View.
<input type="hidden" value="#ViewBag.hdnIsButton1Clicked" id="hdnIsButton1Clicked" name="hdnIsButton1Clicked" />
Set the value of the hidden field and also prevent the default behaviour of submit action.
Jquery
$("#btn1").click(function (event) {
$("#hdnIsButton1Clicked").val("1");
event.preventDefault()
$("[id*=btn2]").click();
})
Add a parameter to get the hidden value and set the viewbag data to be 0 again
Controller
[httpPost]
Public ActionResult MyAction(string hdnIsButton1Clicked){
if(hdnIsButton1Clicked == "1")
{
//user clicked button 1
}
#ViewBag.hdnIsButton1Clicked = "0";
return view();
}
Note - you can set the hidden value true/false. I have given the idea to solve it.
Use code like this :
Changed the button from submit to button. Now HTML will look like this:
<form id="myForm">
....
....
<input type="button" value="Add" id="btn1"/>
<input type="button" value="Add2" id="btn2"/>
</form>
Then the script:
var btn1_cliked = false;
$("#btn1").click(function () {
$(this).attr("name","btn1");
btn1_cliked = true;
$("[id*=btn2]").click();
});
$("#btn2").click(function () {
if(btn1_clicked)
$("button[name='btn1']").removeAttr("name","btn1");
$(this).attr("name","btn2");
$("#myForm").submit();
});
In controller:
Check if $_POST['btn1'] //then btn1 clicked
else // then btn2 clicked
Try this
var flag = 0;
$("#btn1").click(function() {
flag = 1;
$("[id*=btn2]").click();
});
$("#btn2").click(function(e) {
if (flag == 1) {
flag = 0;
alert("from btn1");
} else {
alert("from btn2");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="Submit" value="Add" id="btn1" />
<input type="Submit" value="Add2" id="btn2" />

Meteor: form with two submit buttons (determine button clicked in event handler)

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.

Categories