Hi I have HTML form which I have an onclick event where it prompts the user e.g. if sure yes/no. If no is selected its suppose to stop the form from submitting but it seems to process through as the dialog is being called async. I'm using a jquery plugin http://marcosesperon.es/apps/messi/ for displaying my prompt.
Below is a snippet of my code:
<div id="buttonCommnads">
<button type="submit" class="k-button cancel" id="save" value="Save" title="Save inspection so it may be submitted at a later time" onclick="processCommand(COMMAND.SAVE);">Save</button>
<button type="submit" class="k-button" id="Submit" value="Submit" title="Submit inspection" onclick="return processCommand(COMMAND.SUBMIT);">Submit</button>
#*<button type="submit" class="k-button" id="email" title="Generate draft email for inspection photos" onclick="processCommand(COMMAND.EMAIL);">Email</button>*#
<button type="button" class="k-button" id="cancel" title="Discard changes" onclick="location.href='#Url.Action("Index", "Inspections")'">Cancel</button>
</div>
and then the javascript function:
<script>
var COMMAND = {
SAVE: { value: 0, name: "Save", tense: "saved" },
EMAIL: { value: 1, name: "Email", tense: "emailed" },
SUBMIT: { value: 2, name: "Submit", tense: "submitted" },
};
function processCommand(command) {
if (command == COMMAND.EMAIL) {
}
else if (command == COMMAND.SAVE) {
$('#Submit').val(command.name);
$('#inspectionForm').submit();
}
else if (command == COMMAND.SUBMIT) {
$('#Submit').val(command.name);
var photosAttached = '#Model.Survey.SitePhotoes.Count()';
console.log('processCommand: submit - begin');
if (photosAttached >= 1) {
console.log('processCommand: submit photos attached.');
return true;
} else {
console.log('processCommand: prompt messi.');
new Messi('Are you sure you wish to submit as no inspections photos are currently attached?', {
title: command.name + ' Inspection',
buttons: [{ id: 0, label: 'Yes', val: 'Y', btnClass: 'btn-success' },
{ id: 1, label: 'No', val: 'N', btnClass: 'btn-danger' }],
modal: true,
callback: function (val) {
if (val == 'Y') {
console.log('processCommand: yes.');
return true;
}
else {
console.log('processCommand: no.');
return false;
}
}
});
}
console.log('processCommand: submit - end');
}
}
I'm using ASP.NET MVC 4 and I'm fairly new to web development so please excuse my ignorance. Any help greatly appreciated.
Vince.
The dialog is acting asynchronously and there is no way to prevent this. But what you can do is ensure the form is not submitted on clicking the button and instead submit it from within the callback if appropriate:
Html:
<button type="submit" class="k-button" id="email" title="Generate draft email for inspection photos" onclick="(function() {processCommand(COMMAND.EMAIL);return false;})()">Email</button>
Javascript:
function processCommand(command) {
if (command == COMMAND.EMAIL) {
}
else if (command == COMMAND.SAVE) {
$('#Submit').val(command.name);
$('#inspectionForm').submit();
}
else if (command == COMMAND.SUBMIT) {
$('#Submit').val(command.name);
var photosAttached = '#Model.Survey.SitePhotoes.Count()';
console.log('processCommand: submit - begin');
if (photosAttached >= 1) {
console.log('processCommand: submit photos attached.');
return true;
} else {
console.log('processCommand: prompt messi.');
new Messi('Are you sure you wish to submit as no inspections photos are currently attached?', {
title: command.name + ' Inspection',
buttons: [{ id: 0, label: 'Yes', val: 'Y', btnClass: 'btn-success' },
{ id: 1, label: 'No', val: 'N', btnClass: 'btn-danger' }],
modal: true,
callback: function (val) {
if (val == 'Y') {
console.log('processCommand: yes.');
$("form:first").submit();
}
else {
console.log('processCommand: no.');
}
}
});
}
console.log('processCommand: submit - end');
}
You stop form submission by preventing default action of submit event. click event isn't quite appropriate, as the form can be submitted using the keyboard as well.
In jQuery it's:
$('form').on('submit', function(){
return false;
})
Since your prompt is asynchronous you'll always have to stop normal submission and force submit with form.submit() when user presses "Yes".
event.preventDefault();
Use it to prevent the default behaviour.
More info
I would change the submit buttons to normal buttons (change type="submit" to type="button"). And then, in the function that is triggered by the button, if you evaluate that the user has pressed "yes", submit the form using jQuery:
('#yourFormID').submit();
Otherwise just return false.
Edit: I noticed that you're already triggering the submit() using jQuery, so the button doesn't need to be of the submit type. What happens if you just change the button type to button instead of submit and add a return false in case you don't want to submit anything? Doesn't that do what you meant in your question?
Related
{ field: "Accept", title: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.AcceptChk), "template": "<input type=\"checkbox\" # if (checkCommentsAccept(data.Comments)) { #disabled=\"disabled\" # } # />" },
{ field: "Decline", title: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.DeclineChk), "template": "<input type=\"checkbox\" # if (checkCommentsDecline(data.Comments)) { #disabled=\"disabled\" # } # />" },
{ field: "Item", title: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.Item) },
{ field: "PartID", title: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.PartID) },
{ field: "Description", title: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.Description), width: '300px' },
{ field: "SubPart", title: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.SubPart) },
{ field: "SubPartDescription", title: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.SubPartDescription) },
{ field: "BusinessPartner", title: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.BusinessPartner) },
{ field: "ReqDelTM", title: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.ReqDelTM) },
{ field: "EarDelTM", title: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.EarDelTM) },
{ field: "EarDelDate", title: "Ear Del Date", hidden: true },
{ field: "Comments", title: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.Comments) }
When i click submit button it should check accept checkbox is checked or not if is checked then i have some logic. If decline check box is checked then i have some other logic.
This really just comes down to how to stop an event from performing its native behavior.
If a submit button is pressed, the form's submit event is triggered. So, if your checkbox isn't checked at that time, you'll need to stop the event, which is done with event.preventDefault(). If the checkbox is checked, simply don't do anything and allow the submit to happen.
Here's an example:
// Get reference to the checkbox
let chk = document.querySelector("input[type='checkbox']");
// Set up event handler on the form
document.querySelector("form").addEventListener("submit", function(event){
// Check to see if the checkbox was not checked
if(!chk.checked){
event.preventDefault(); // Stop the submit event
alert("You must agree before continuing.");
return;
}
// If we get to this point in the code, the checkox was checked
// and the form will submit.
});
<form action="http://example.com" method="post">
<input type="checkbox" name="chkAgree"
id="chkAgree" value="agree">
I agree to the terms of this site.
<br>
<button>Submit</button>
</form>
if there is checkbox you might have implemented that only single checkbox is checked right ?, other wise there might be possibility that Accept & Declined both checkbox are checked ,
assuming that you have implemented single select checkbox logic
$( "form" ).submit(function( event ) {
event.preventDefault();
if($("input[type='checkbox']:checked")[0].val() == 'Allow'){
// things to done on allowed
}else if($("input[type='checkbox']:checked")[0].val() == 'Declined'){
// things to done on declined
}else{
// rest things
}
});
you might need to change code a bit , but it will logically work as per your need.
I am currently using Django 1.9 and Braintree payments JS v3. What I want to be able to do is when the user submits the form successfully, have a Javascript alert() pop up. But the pop-up message will be contingent on what the back end Python returns...
So like this:
Submit the form
Run the backend stuff
Pop up the alert with a message dependent on what is returned by the Python backend
When the alert is closed, refresh or redirect
var client_token = "{{ request.session.braintree_client_token }}"
var form = document.querySelector('#checkout-form');
var submit = document.querySelector('input[type="submit"]');
braintree.client.create({
authorization: client_token
}, function (clientErr, clientInstance) {
if (clientErr) { // for error loading client authorization
if(alert('There was a form verification issue, reloading page on close.')){}
else window.location.reload();
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '14px'
},
'input.invalid': {
'color': 'red'
},
'input.valid': {
'color': 'green'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: 'Credit Card Number'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationDate: {
selector: '#expiration-date',
placeholder: '10/2019'
},
postalCode: {
selector: '#postal-code',
placeholder: '10014'
}
}
}, function (hostedFieldsErr, hostedFieldsInstance) {
if (hostedFieldsErr) { // for errors creating form
if(alert('There was a form creation issue, reloading page on close.')){}
else window.location.reload();
return;
}
submit.removeAttribute('disabled');
form.addEventListener('submit', function (event) {
event.preventDefault();
document.querySelector('input[id="pay-button"]').value = "Please wait...";
hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
if (tokenizeErr) {
if (tokenizeErr.code === 'HOSTED_FIELDS_FIELDS_EMPTY') {
alert('Please fill in card info');
document.querySelector('input[id="pay-button"]').value = "Complete Booking";
}
return;
}
// Put `payload.nonce` into the `payment_method_nonce`
document.querySelector('input[name="payment_method_nonce"]').value = payload.nonce;
form.submit();
$('input[type="submit"]').prop('disabled',true);
});
}, false);
});
});
I'm thinking that this functionality would need to be right after form.submit() is run on the bottom...
Edit:
I added the vars up top in my code
Here is my form
<form method="POST" action="adddriverprocess.php" enctype="multipart/form-data">
<...>
<...>
</form>
It works good in the submit <input type="submit" value="Submit"/>
I am trying to have the jquery popup in it, where by pressing the form should do the post action.
So, i had this jquery button
<button class="delete-btn btn-sm"><span class="icon"></span></button></td>
With
$('.btnActivation').click(fnActivation);
function fnActivation() {
var url =$(this).attr("id");
$("#dialog-confirms").html("Are you sure you want to submit this form ?");
var buttonsConfig = [
{
text: "Yes",
"class": "ok",
click: function() {
$(this).dialog('close');
window.location.href=url;
}
},
{
text: "Cancel",
"class": "cancel",
click: function() {
$(this).dialog('close');
}
}
];
$("#dialog-confirms").dialog({
resizable: false,
modal: true,
title: "Ma$na Taxi",
height: 250,
width: 400,
buttons: buttonsConfig,
});
}
The popup comes good, but when i press the ok button it takes me to the adddriverprocess but in get method but i want it to do in post method with the datas that is filled in the name.
How can i do this ?
Put an ID on your form and change your "Yes" click function to post your form instead of the location.
Change this:
click: function() {
$(this).dialog('close');
window.location.href=url;
}
To this:
click: function() {
$('#MyForm').submit();
$(this).dialog('close');
}
Here's the jQuery submit() documentation:
http://api.jquery.com/submit/
I am using bootbox dialogs for confirming before deleting records.
here is my jQuery script for confirmation before deleting record.
<a class="btn btn-xs btn-danger" id="deleteContent" title="Delete">delete</a>
$('#deletec').click(function (e) {
bootbox.dialog({
message: "you data is save",
title: "Custom title",
buttons: {
success: {
label: "Success!",
className: "btn-success",
callback: function () {
Example.show("great you save it");
}
},
danger: {
label: "Danger!",
className: "btn-danger",
callback: function () {
Example.show("record deleted!");
}
}
}
});
});
it is showing correct dialog but the record being deleted without taking confirmation, can anyone please tell me how can i prevent deletion of record without confirmation ? Thanks in advance.
You can not do what you want because the modal dialog that you are using has no way of pausing the click action. You would need to have to cancel the click action and than make that call.
One way is just to unbind click and call it again
$('#deleteContent').on("click", function (e) {
e.preventDefault();
bootbox.dialog({
message: "you data is save",
title: "Custom title",
buttons: {
success: {
label: "Success!",
className: "btn-success",
callback: function () {
Example.show("great you save it");
}
},
danger: {
label: "Danger!",
className: "btn-danger",
callback: function () {
Example.show("record deleted!");
$('#deleteContent').off("click")[0].click();
}
}
}
});
});
As I said in my comments above, making a delete request with a get is a BAD idea. If a user has a plugin that prefetches pages, say goodbye to all your data in the database.
What happens in the code
e.preventDefault(); Cancels the click event so it will not go to the server
$('#deleteContent').off("click") //removes the click event so it will not be called again
[0].click() //selects the DOM element and calls the click event to trigger the navigation
I have a form that when the submit is hit i want a modal box to pop up with a YES and NO button i want the both the yes and no button to submit the form but i need to know which button they clicked.
Here is my code
<input onclick="$.msgbox('confirm text',{
buttons : [
{type: 'submit', value:'YES'},
{type: 'submit', value:'NO'}
]
}, function(buttonPressed) {
});" name="btnApply" id="btnApply" tabindex="41" src="images/btnsubmit.jpg" style="border-width: 0px;" type="image" />
My problem is the form is submitting when the user clicks submit.
Any help or ideas would be great
thanks
While I'm not familiar with the $.msgbox plugin but you should be opening the modal dialog on <form> submit and not on a button press, as the form can also be submitted by an enter/return on certain input fields (like text boxes <input type="text|password">)
var confirmed = false;
$('#myform').bind('submit', function() {
if (confirmed) {
return true; // confirmation received, continue form submission process
} else {
$.msgbox(
'my modal message',
{
buttons : [
{ type: 'button', value: 'YES' },
{ type: 'button', value: 'NO' }
]
},
function(buttonPressed) {
confirmed = buttonPressed.value; // Update the confirmed variable
$('#myform').submit(); // re-submit the form
}
);
return false; // cancel form submission
}
});
Add return false:
<input onclick="$.msgbox('Would you like a cash advance of up to £1000 whilst we process your loan?',{
buttons : [
{type: 'submit', value:'YES'},
{type: 'submit', value:'NO'}
]
}, function(buttonPressed) {
}); return false;" name="btnApply" id="btnApply" tabindex="41" src="images/btnsubmit.jpg" style="border-width: 0px;" type="image" />
Not sure about the msgbox either but some remarks about your code:
Don't attach your JS logic directly to your code, but use jQuery to attach click event to your markup (see unobtrusive javascript):
Instead of
<input onclick="$.msgbox('confirm text',{
Use
$('#btnApply').click(function(e) {
You can stop the click handling by setting as false one property of the event parameter:
$('#btnApply').click(function(e) {
e.preventDefault(); // stop click handling and so form submitting
Finally, handle the form submitting or not in the msgbox callback function:
$.msgbox("Are you sure that you want to permanently delete the selected element?", {
type: "confirm",
buttons: [
{
type: "submit",
value: "Yes"},
{
type: "submit",
value: "No"},
{
type: "cancel",
value: "Cancel"}
]
}, function(result) {
if(result == "Yes") // display the form on submit
$('form').submit();
});
jsFiddle available.