Handling submit and preventing submit on jQuery - javascript

Script:
<script type="text/javascript">
var modifyActionURL;
$(document).ready( function() {
modifyActionURL = function(obj) {
if (($('.checkboxclass:checked').length == 1)) {
$("#searchForm").attr("action", obj);
} else if ($('.checkboxclass:checked').length > 1) {
$("#dialogOnlyOne").dialog({
height: 200,
width: 500,
modal: true,
open: function (type, data) {
$('.ui-dialog').css('z-index', 9999);
$(this).parent().appendTo("form");
},
close: function(event, ui) {
$("#dialogOnlyOne").hide();
},
buttons: [
{
text: "Ok",
type: "button",
click: function() {
$(this).dialog("close");
}
}
]
});
} else {
alert('Please select a row');
}
};
</script>
HTML:
<form id="searchForm" action="#" th:object="${search}" method="post">
<div id="dialogOnlyOne" class="window">
<p style="background-color: #ffffff">Please select only one row.</p>
</div>
<input type="submit" value="Modify" class="btn btn-primary" id="modify" th:onclick="'javascript:modifyActionURL(\'' + #{/search/modify} + '\')'" />
</form>
When the checked length is 1, the page should be submitted. When the length is greater than one, dialog box should be displayed and on click of ok, the dialog box should close without submitting or refreshing the page. Can anyone help on this.

You need to return false from the function to prevent the form from submitting.
$(document).ready( function() {
modifyActionURL = function(obj) {
if (($('.checkboxclass:checked').length == 1)) {
$("#searchForm").attr("action", obj);
} else if ($('.checkboxclass:checked').length > 1) {
$("#dialogOnlyOne").dialog({
height: 200,
width: 500,
modal: true,
open: function (type, data) {
$('.ui-dialog').css('z-index', 9999);
$(this).parent().appendTo("form");
},
close: function(event, ui) {
$("#dialogOnlyOne").hide();
},
buttons: [
{
text: "Ok",
type: "button",
click: function() {
$(this).dialog("close");
}
}
]
});
return false; // prevent form submission
} else {
alert('Please select a row');
return false; // prevent form submission
}
};
});
You also need to return the value of the function in the onclick:
<input type="submit" value="Modify" class="btn btn-primary" id="modify" th:onclick="'return modifyActionURL(\'' + #{/search/modify} + '\')'" />
BTW, you don't need javascript: in onXXX attributes. That's only needed when you put Javascript in an attribute that normally contains a URL, like href.

I guess you should use a onsubmit event attached to your form, instead of the onclick event directly on the submit button.
There is clear exemple of using the onsubmit event with jQuery here
https://api.jquery.com/submit/
To prevent the form from submitting you will have something close to
$( "#target" ).submit(function( event ) {
alert( "Handler for .submit() called." );
event.preventDefault();
});

Related

Clearing jQuery Dialog validate upon open

I am encountering similar behaviour in my code: https://codepen.io/iw3/pen/BAdIq
html
<input id="open" type="button" value="Open" />
<div id="dialog">
<form id="form">
<input type="text" name="field" />
</form>
</div>
JS
$(function () {
$('#dialog').dialog({
autoOpen: false,
buttons: {
'Send': function() {
if ($('#form').valid()) {
alert('Success');
$('#dialog').dialog('close');
}
}
}
});
$('#open').on('click', function() {
$('#dialog').dialog('open');
});
$('#form').validate({
rules: {
field: {
required: true,
digits: true,
maxlength: 9,
min: 1
}
}
});
});
When the user enters data in the form and gets an error, then closes the form and reopens it, the validate messages in red remain while they should really be cleared. Is this an intended behavior or is there a way to reset the validate?
To fix this you can simply hide the validation error label elements when the dialog is closed:
$('#dialog').dialog({
autoOpen: false,
close: function() {
$('label.error').hide();
},
// other configuration settings...
});
Alternatively you can save a reference to the validator and call resetForm() on it when the dialog is closed:
let validator = $('#form').validate({
rules: {
// your rules...
}
});
$('#dialog').dialog({
autoOpen: false,
close: function() {
validator.resetForm();
},
// other configuration settings...
});

Jquery-ui Tabs Open dialog box on tab click (stop code)

This is my code. I am trying to stop the clicked tab from loading until i get a response from the dialog box. Also if i click cancel, i wan to return to the previously selected tab. currently the way i have it setup it creates a loop (which i broke with my lame code).
As seen in my jsfiddle example the code does stop. However, you will notice in the backround that the tab does change to the clicked one, so if you click cancel the backround will flash. i am trying to avoid that.
Thanks.
My Fiddle
//
var runOnceDammit;
$(document).ready(function() {
$(".hideT").button();
$("#tabs").tabs();
$("#tabs").tabs("disable", "#tabs-4");
$('.ms-formtable').appendTo($('#tabs-1'));
$("#tabs").on("tabsbeforeactivate", function(event, ui) {
if (runOnceDammit == true) {
runOnceDammit = false;
return;
}
var active = $("#tabs").tabs("option", "active");
var dialResults = $.when(showDialog());
dialResults.done(function(data) {
if (data) {
$('.ms-formtable').appendTo(ui.newPanel);
if (ui.newPanel.is("#tabs-2")) {
//do stuff
} else if (ui.newPanel.is("#tabs-3")) {
//do stuff
} else if (ui.newPanel.is("#tabs-1")) {
//do stuff
}
return;
} else {
ui.newTab.blur(); //trying to remove higlight from tab
runOnceDammit = true
$("#tabs").tabs({
active: active
}); //activate previous tab
return;
}
});
//return;
});
}); //End DocReady!
//
//
function showDialog() {
var dfd = $.Deferred();
var results;
$('#dialog').dialog({
dialogClass: "no-close",
title: "Fanciful Dialog Box",
modal: true,
draggable: false,
buttons: [{
text: 'Confirm',
icons: {
primary: "ui-icon-check"
},
click: function() {
results = true;
$(this).dialog('close');
}
}, {
text: 'Cancel',
icons: {
primary: "ui-icon-cancel"
},
click: function() {
results = false;
$(this).dialog('close');
}
}],
close: function(event, ui) {
dfd.resolve(results);
}
});
return dfd.promise()
}
Consider the following:
<div class="section" id="section-1">
Tab 1
</div>
<div class="section" id="section-2">
<a name="myTab-1"></a>
</div>
<script>
$("#myTab-1").click(function(event){
event.preventDefault();
// Do a thing
return true;
});
</script>
This jQuery code will bind an anonymous function to the click event. The function takes a JavaScript Event Object as an attribute. Events have some methods to them, such as, .preventDefault(). This allows you to interrupt the default event and execute your own code. Using return true will return the default behavior after your code has been run.
I answered a similar question: confirm form submit with jquery UI
I found it better to resolve with the result. It seems that .resove() will work out better this way when it comes to the .done() code.
Working example: https://jsfiddle.net/Twisty/e2djqx08/
The key, I think, was to assign the active tab properly in your cancellation code.
JavaScript
function showDialog() {
var dfd = $.Deferred();
var results;
$('#dialog').dialog({
dialogClass: "no-close",
title: "Fanciful Dialog Box",
modal: true,
draggable: false,
buttons: [{
text: 'Confirm',
icons: {
primary: "ui-icon-check"
},
click: function() {
$(this).dialog('close');
dfd.resolve(true);
}
}, {
text: 'Cancel',
icons: {
primary: "ui-icon-cancel"
},
click: function() {
$(this).dialog('close');
dfd.resolve(false);
}
}]
});
return dfd.promise();
}
$(function() {
$("#tabs").tabs().tabs("disable", 3);
$('.ms-formtable').appendTo($('#tabs-1'));
$("#tabs").on("tabsbeforeactivate", function(e, ui) {
e.preventDefault();
console.log("EVENT: Prevent Default");
var self = $(this);
var revertToTab = ui.oldTab;
var revertToPanel = ui.oldPanel;
var sendTo = ui.newTab;
var sendToPanel = ui.newPanel;
console.log("EVENT: When Dialog is closed.");
$.when(showDialog()).done(function(data) {
if (data) {
console.log("INFO: Dialog Confirmed.");
$('.ms-formtable').appendTo(ui.newPanel);
if (self.is("#tabs-2")) {
//do stuff
} else if (self.is("#tabs-3")) {
//do stuff
} else if (self.is("#tabs-1")) {
//do stuff
}
return;
} else {
console.log("INFO: Dialog Cancelled");
self.blur();
$("#tabs").tabs("option", "active", revertToTab);
return false;
}
});
});
});
In my tests, I continued to find the active tab panel loading while the dialog was active. This did not happen when I used $("#tabs").tabs("option", "active", revertToTab);.
Hope that helps.

jquery UI modal not causing postback

I have a jquery UI modal which opens on checkbox click and cause postback after clicking ok button but its not working .I have tried all solutions.please help.Asp.net button is inside form tag.
$("#dialog").dialog({
modal: true,
autoOpen: false,
title: "Other-Legend",
width: 300,
open: function (type, data) {
$(this).parent().appendTo("form");
},
buttons: {
Ok: function () {
$("[id*=btnConfirm]").click();
},
Close: function () {
$(this).dialog('close');
}
}
});
jQuery('input[type="checkbox"]').click(function () {
var parentClass = jQuery(this).parent('td').attr('class');
var checked = jQuery(this);
jQuery('.' + parentClass.substring(0, parentClass.length - 8) + ' input[type="checkbox"]').each(function (i, e) {
jQuery(this).prop('checked', false);
})
jQuery(checked).prop('checked', true);
if (parentClass.indexOf("mdclass") >= 0) {
$('#dialog').dialog('open'); }
});
<asp:Button ID="btnConfirm" runat="server" Text="Button" style="display:none" OnClick ="Button1_Click" />
You can try adding the jQuery UI v1.10 or greater syntax of appending the modal DIV to the form.
$("#dialog").dialog({
modal: true,
autoOpen: false,
title: "Other-Legend",
width: 300,
appendTo: "form",
buttons: {
Ok: function () {
$("[id*=btnConfirm]").click();
},
Close: function () {
$(this).dialog('close');
}
}
});

jQuery UI dialog: How check what if user confirm or cancel the UI dialog.

I have this code:
HTML:
<div id="dialog-first"></div>
<div id="dialog-second"></div>
<div id="dialog-third"></div>
<div id="menu">
<ul>
<li id="first">first</li>
<li id="second">second (need confirm)</li>
<li id="third">third (need confirm)</li>
</ul>
</div>
Javascript part 1:
$('li a.confirm').live('click', function (e) {
e.preventDefault();
var id = $(this).parent('li').attr('id');
$('#dialog-' + id).dialog({
dialogClass: 'ui-dialog-confirm',
buttons: {
"Confirm": function () {
/*window.location.href = $(this).attr('href');*/
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
});
Javascript part 2:
$('#menu li').each(function () {
var id = $(this).attr('id');
$('#dialog-' + id).on("dialogclose", function (event, ui) {
//How can I check what user clicked, Confirm or Cancel ???
//Is it possible
console.log(event);
});
});
How can I check what user clicked, Confirm or Cancel ???
If possible I would like change Javascript part2 only.
Change the structure of your buttons code to:
buttons: [{
text: "Confirm",
click: function () {
$(this).dialog("close");
console.log('confirm')
}
}, {
text: "Cancel",
click: function () {
$(this).dialog("close");
console.log('cancel')
}
}]
Then you have easy access to the click event for each button.
jsFiddle example

How to re-use jQuery UI Dialog by changing dialog options

I know the correct way to manage JQuery.dialog is to initialize with:
$("#dialog").dialog({ autoOpen: false });
Then use the following to open and close it:
$("#dialog").dialog("open");
$("#dialog").dialog("close");
But there are some cases when this model is not fully applicable.
For instance, I use a dialog to create new data and to edit existing data. In the first case I have a cancel and a create button, but in the second case I have also a delete button.
I've seen that there is a destroy function in jquery.dialog. The question is: in these cases, should I destroy the dialog instead of close it and create a new one? There is any better option?
jQuery UI dialog allows you to manipulate most properties after initialization. You can change the buttons some time after the dialog is initialized; e.g. when the insert or update button is clicked.
// imported from http://jsfiddle.net/salman/VYAJw/9/
$(function() {
$("#dialog1").dialog({
autoOpen: false,
modal: true
});
$("#button-insert").click(function() {
$("#dialog1").dialog("option", "title", 'Insert Record');
$("#dialog1").dialog("option", "buttons", [{
text: "Insert",
click: function() {
alert("Record inserted");
$(this).dialog("close");
}
}, {
text: "Cancel",
click: function() {
$(this).dialog("close");
}
}]);
$("#dialog1").dialog("open");
});
$("#button-update").click(function() {
$("#dialog1").dialog("option", "title", 'Update Record');
$("#dialog1").dialog("option", "buttons", [{
text: "Update",
click: function() {
alert("Record updated");
$(this).dialog("close");
}
}, {
text: "Delete",
click: function() {
alert("Record deleted");
$(this).dialog("close");
}
}, {
text: "Cancel",
click: function() {
$(this).dialog("close");
}
}]);
$("#dialog1").dialog("open");
});
});
#import url("https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/blitzer/jquery-ui.min.css");
body {
font: medium sans-serif;
}
#dialog1 label,
#dialog1 input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div id="dialog1">
<p>Fill out this form.</p>
<form>
<fieldset>
<label for="name">Name</label>
<input type="text" name="name" id="name" />
<label for="email">Email</label>
<input type="text" name="email" id="email" />
<label for="password">Password</label>
<input type="password" name="password" id="password" />
</fieldset>
</form>
</div>
<input type="button" id="button-insert" value="Insert" />
<input type="button" id="button-update" value="Update" />
An alternate method would be to add the buttons directly inside the form and .hide() them depending on whether you're showing insert or update dialog.
you can set different buttons as option before dialog open
e.g.
var buttons = {
"act_add": {
"Insert": function() { ... },
"Cancel": function() { ... }
},
"act_edit": {
"Save": function() { ... },
"Delete": function() { ... }
}
};
$('.dialogOpenLink').click(function(){
var $dlg = $('#dialog'),
actType;
//get an action name from data attribute of the clicked element
actType = $(this).data('action'); //or get the action in way that best suits you
$dlg.dialog( "option", "buttons", buttons[actType]);
$dlg.dialog('open');
});
To safelly remove dialog all you need is to set close option like this:
close: function() {
return $(this).remove();
}

Categories

Resources