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.
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.
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've trouble getting values out of my form.
I'm using bootstrap dialog from nakupanda (http://nakupanda.github.io/bootstrap3-dialog/)
The dialog (it is in a fullcalendar select function)
http://arshaw.com/fullcalendar/docs/selection/select_callback/
var form = $('#createEventForm').html();
BootstrapDialog.show({
message: form,
buttons: [{
label: 'Enkel rooster event',
action: function(dialogItself){
console.log('enkel - create')
dialogItself.close();
}
},{
label: 'Herhalend rooster event (elke dag)',
action: function(dialogItself){
console.log('meer - create')
dialogItself.close();
}
},{
label: 'Close',
action: function(dialogItself){
console.log(dialogItself);
alert('The content of the dialog is: ' + dialogItself.getModal().html());
}
}]
});
The html form
<form id="createEventForm">
<label>Klantnaam</label>
<input type="text" id="titleDrop" />
<br/>
<label>Beschrijving</label>
<input type="text" id="descriptionDrop" />
</form>
I don't know how to retrieve the data from the forms input when someone clicks on a button. I've tried $(titleDrop).val()andgetElementById(titleDrop)
Sometimes the form can contain php.
I am not getting javascript errors. I just don't get anything back when clicking on the butotns and using $('titleDrop').val()
EDIT FIDDLE
http://jsfiddle.net/jochem4207/7DcHW/3
This code works:
var form = '<label>Klantnaam</label><input type="text" id="titleDrop"><br><label>Beschrijving</label><input type="text" id="descriptionDrop">';
BootstrapDialog.show({
message: form,
buttons: [{
id: 'submit1',
label: 'See what you got',
cssClass: 'btn-primary',
action: function(dialogRef){
var titleDropVal = $('#titleDrop').val();
console.log(titleDropVal);
}
}]
});
Still curious if it could work when I dont add the html in the JS section.
Edit: Question 2
I have a select list that gets filled from php
var select = $('<select id="selectVisibleUser"></select>');
<?php
$userList = array();
foreach($this->users as $user){
$jsUser = array(
'key' => $user->webuserId,
'value'=> $user->firstName.$user->preposition.$user->lastName
);
array_push($userList, $jsUser);
}
$list = Zend_Json::encode($userList);
?>
$.each(<?php echo $list?>, function(key, value) {
select.append($("<option/>", {
value: key,
text: value
}));
});
BootstrapDialog.show({
message: function (dialogItself){
var form = $('<form></form>');
dialogItself.setData('select-visible', select);
form.append('<label>Select</label>').append(select);
return form;
},
buttons: [{
id: 'submit1',
label: 'See what you got',
cssClass: 'btn-primary',
action: function(dialogItself){
alert(dialogItself.getData('select-visible').val());
}
}]
});
This shows me a empty select list and returns offcourse a null when I click the button.
Should I use your first fiddle in this case?
Tried the first fiddle ( http://jsfiddle.net/b8AJJ/1/ ) works perfectly in this case (except i've some trouble to get the id instead of the value)
Try this:
http://jsfiddle.net/b8AJJ/
If possible I would suggest this way:
http://jsfiddle.net/7DcHW/4/
BootstrapDialog.show({
message: function (dialogItself) {
var $form = $('<form></form>');
var $titleDrop = $('<input type="text" />');
dialogItself.setData('field-title-drop', $titleDrop); // Put it in dialog data's container then you can get it easier by using dialog.getData() later.
$form.append('<label>Title Drop</label>').append($titleDrop);
return $form;
},
buttons: [{
label: 'Get title drop value.',
action: function (dialogItself) {
alert(dialogItself.getData('field-title-drop').val());
}
}]
});
You're using element selector wrong.
Try $('#titleDrop').val() instead of $(titleDrop).val().
Bind submit event to your form. This way you can get the values of form inputs when the form is submitted. Look at the following example:
http://jsbin.com/xiruv/1/
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?
I want to disable the submit button when a user submits the form so that he may not click the submit button twice.
So I coded the following javascript in my page
$(document).ready(function(){
$("form").submit(function(){
$("form").find('input[type=submit]').attr('disabled', 'disabled');
});
})
This works great. But when I applied the jquery validate library and appended the following code
$(document).ready(function(){
$("form").submit(function(){
$("form").find('input[type=submit]').attr('disabled', 'disabled');
});
$("form").validate({
errorClass: "jqueryError",
errorElement: 'label',
success: 'jqueryValid',
messages: {
TopicCategory: {
required: 'Please choose a category for topic.'
},
TopicSubcategoryId: {
required: 'Please choose a subcategory for topic.'
},
TopicTitle: {
required: 'Please enter a title for topic.'
}
}
});
})
The submit button got disabled after submitting form even if there are incomplete inputs in the website (i.e. form with errors and user is asked to fill them properly).
and when the user completes the form correcting all errors the submit button is disabled.
How do I first check if there are no errors in the form and then disable the submit button and then submit it finally.
Thanks
Add the following parameter to jQuery Validate:
submitHandler: function(form) {
$(':submit', form).attr('disabled', 'disabled');
form.submit();
}
I have not used the jquery validator plugin but reading the docs here
http://docs.jquery.com/Plugins/Validation/validate
you could
1) disable the button in the submitHandler callback
2) leave your existing disable code, but then re-enable the button in the invalidHandler callback
I have not started with jQuery yet. But I think, you can do something like this:
$(document).ready(function(){
$("form").submit(function(){
});
$("form").validate({
errorClass: "jqueryError",
errorElement: 'label',
success: 'jqueryValid',
messages: {
TopicCategory: {
required: 'Please choose a category for topic.'
},
TopicSubcategoryId: {
required: 'Please choose a subcategory for topic.'
},
TopicTitle: {
required: 'Please enter a title for topic.'
}
}
$("form").find('input[type=submit]').attr('disabled', 'disabled');
});
})