Reputation: 35
I'm try to using reusable jquery ui modal dialog box, and after searching in this forum I found solution like this (thanks for user ash)
Create Dialog Class
function OkDialog() {
this.showMessage = function(message) {
var $dialog = $('<div></div>')
.html(message)
.dialog({
modal: true,
closeOnEscape: true,
buttons: {
Ok: function() {
$(this).dialog("close");
}
}
});
$dialog.dialog("open");
}
}
Create a global object in one of the common file(jsp)
OK_DIALOG = new OkDialog();
Call this function with desirable message
OK_DIALOG.showMessage("You don't have more than a single penny.");
I tried and it works well.
my code :
html :
<label>Your Name</label> : <input type="text" id="your_name"/>
<label>Your Country</label> : <input type="text" id="your_country"/>
<button type="button" id="save_button">Save</button>
jQuery :
$(document).ready(function() {
$('#save_button').on('click', function(e) {
var your_name = $('#your_name').val();
if ($.trim(your_name).length==0) {
OK_DIALOG = new OkDialog();
OK_DIALOG.showMessage("Please fill your name!");
$('#your_name').focus();
return false;
}
}
});
When I click save_button, modal and focus work together, and after i click ok button, focus disappeared.
So, My question is how to focus to element after close the modal?
Upvotes: 2
Views: 1796
Reputation: 1105
Just go through the code below. Here i have pass the id of the control which should be focused on close event of the modal window.
In jquery ui modal there is an event called close which triggers when the modal is closed. Inside that event we made focus to that control. So it's works.
function OkDialog() {
this.showMessage = function(message,control_Id="") {
var $dialog = $('<div></div>')
.html(message)
.dialog({
modal: true,
closeOnEscape: true,
close: function() {
if(control_Id!="")
$(control_Id).focus();
},
buttons: {
Ok: function() {
$(this).dialog("close");
}
}
});
$dialog.dialog("open");
}
}
$(document).ready(function() {
$('#save_button').on('click', function(e) {
var your_name = $('#your_name').val();
if ($.trim(your_name).length==0) {
OK_DIALOG = new OkDialog();
OK_DIALOG.showMessage("Please fill your name!",'#your_name');
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<label>Your Name</label> : <input type="text" id="your_name"/>
<label>Your Country</label> : <input type="text" id="your_country"/>
<button type="button" id="save_button">Save</button>
Upvotes: 1