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

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();
}

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 and Bootstrap Dialog

$('.inputCheck').unbind().on('click', function() {
if ($('#exampleInputPassword').prop('disabled'))
$('#exampleInputPassword').prop('disabled', false);
else
$('#exampleInputPassword').prop('disabled', true);
});
BootstrapDialog.show({
title: 'Example',
message: '<input type="checkbox" class="inputCheck"/>Check <input type="password" class="form-control" id="exampleInputPassword" placeholder="Password">',
buttons: [{
label: 'Close',
action: function(dialog) {
dialog.close();
}
}]
});
How can I apply jQuery to access element in BootstrapDialog? The code above should behave like this, if $('.inputCheck') is clicked, $('#exampleInputPassword') should be disabled or enabled based on its state.

Handling submit and preventing submit on jQuery

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();
});

Javascript events inside bootstrap popup (bootbox) dont work

I´m trying create a bootstrap popup with bootbox modal, inside of form has a input text with masked input, but any events inside of popup don´t work.
See here: http://jsfiddle.net/ens1z/UK6x5/5/
The html:
<p>The mask input below WORKS great</p>
<p>
<input type="text" class="mask" />
</p>
OPEN BOOTBOX
<div id="frm" style="visibility: hidden">
<div class="form-horizontal">
<p>The mask input below DON´T WORK. :-(</p>
<input type="text" class="mask"/>
</div>
</div>
JavaScript:
$("#asssf").click(function (e) {
e.preventDefault();
bootbox.dialog({
message: $("#frm").html(),
title: "Custom title",
buttons: {
success: {
label: "Success!",
className: "btn-danger",
callback: function() {
return;
}
}
}
});
$(".mask").mask("999-99-9999",{placeholder:"_"});
});
$(".mask").mask("999-99-9999",{placeholder:"_"});
How to mask works inside of popup?
Try this fiddle :) HERE
The problem is that you loaded the html to bootbox without his events.
i made a function to solve your problem:
function BootboxContent(){
var content = $("#frm").clone(true);
$(content).css('visibility','visible');
content.find('.mask').mask("999-99-9999",{placeholder:"_"});
return content ;
}
call it on your message as in the fiddle, or without function like this :
bootbox.dialog({
message: $("#frm").clone(true).css('visibility','visible').find('.mask').mask("999-99-9999",{placeholder:"_"}),
title: "Custom title",
buttons: {
success: {
label: "Success!",
className: "btn-danger",
callback: function() {
return;
}
}
}
});
});

how to set focus on jquery confirm dialog

i have a simple jquery confirm dialog and wants to set focus on dialog itself rather on any other element. code below is what i did to set focus on:
function showAlert() {
$("#dialog-confirm").dialog({
title: 'Main Information',
resizable: false,
height:140,
modal: true,
closeOnEscape:true,
buttons: {
"Yes": function() {
document.getElementById('form1:newProfile' ).value="true";
if(disableSaveFlag) return false; else disableEnableSaveBtn('true');
$( this ).dialog( "close" );
},
"No": function() {
document.getElementById('form1:newProfile' ).value="false";
if(disableSaveFlag) return false; else disableEnableSaveBtn('true');
$( this ).dialog( "close" );
}
}
});
$("#dialog-confirm").focus(); // this line sets focus on div element with given id
}
<div id="dialog-confirm" style="display:none">
<p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>
Do you want to create a new profile ?
</p>
</div>
problem is i cannot find "Id" of a dialog itself to being focus on to it.
As a result focus is set on Div element and my title is not focused.
below is what i get with above code:
Just press Tab and it will focus the first element of the dialog.
I guess we can focus anything on below event. I just tried and working fine for me..
onContentReady: function () {
//select the element you want to focus here
$(".btn-success").focus();
}
So my full code looks like this. In this case I am focusing the Button on my dialog.
$.confirm({
icon: "fas fa-check-square",
title: " Completed!",
content: "Action Plans Updated Successfully!",
type: "green",
typeAnimated: true
buttons: {
Complete: {
text: "Complete",
btnClass: "btn-success",
action: function () {
location.reload(true);
},
},
},
onContentReady: function () {
$(".btn-success").focus();
},
});

Categories

Resources