Retrieve input value from Jquery UI dialog box - javascript

I am working on a small project (just a practice example - not for real use). Its a very simple CRUD application, and I am not aloud to alter the index.html. Also have to use JQuery UI Dialog and not prompt().
I got up to ADD functionality and I'm stuck. I've created a Jquery UI dialog that appends a form - its triggered when 'Add item' is clicked. Then The action for clicking 'yes' in the form needs to return what was in the input. I am unable to retrieve the value and there is no server side technology(like php)involved. function add_item() in answers.js is where I am working now.
I also don't know why, but an additional input box appears on the bottom of my html page after clicking 'Add item' (it should only append to the form )
*Note: CRUD functions begin after document.ready...lower on the page.
Also, besides the one default item in index.html list items are originally from a json file
*
answer.js
$(document).ready(function()
{
///////// REMOVE ALL ////////////
$(document).on("click", "div a:nth-of-type(3)", function(e)
{
e.preventDefault();
remove_all();
});
$("div a:nth-of-type(3)").click(remove_all);
///////// ADD ITEM ////////////
$(document).on("click", "#add_item", function(e)
{
e.preventDefault();
add_item();
});
$("#add_item").click(add_item);
///////// LOAD ALL ////////////
$(document).on("click", "div a:nth-of-type(2)", function(e)
{
e.preventDefault();
load_all();
});
///////// REMOVE ITEM ////////////
$(document).on("click", "#my_list a", function(e)
{
e.preventDefault();
var current_item = $(this).parent();
remove_item(current_item);
});
$("#my_list a").click(remove_item(current_item));
///////// EDITABLE ITEM ////////////
});
/// CRUD FUNCTIONS ////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
function add_item()
{
$('body').append('<div id="dialog-form"><form> Add your item:<br><input type="text" name="new_item" id="new_item" ></form></div>');
// JQUERY UI DIALOG
$( "#dialog-form" ).dialog({
resizable: false,
title:'Add new item',
height:240,
width:260,
modal: true,
buttons: {
"Yes": function() {
var test = $('#new_item').val();
alert(test);
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
}
function remove_all()
{
$('#my_list li').hide();
}
function load_all()
{
$.getJSON( "myLists/myList.json", function( json )
{
var items = json;
$('#my_list li').remove();
$.each(items, function(index,the_item)
{
$('#my_list').append('<li>'+the_item+'x</li>')
});
});
}
function remove_item(current_item)
{
// APPEND DIALOG BOX DIV
$('<div id="dialog-confirm">').appendTo('body');
// JQUERY UI DIALOG
$( "#dialog-confirm" ).dialog({
resizable: false,
title:'Remove this item?',
height:140,
width:260,
modal: true,
buttons: {
"Yes": function() {
$(current_item).hide();
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
}
INDEX.HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<link href="jquery-ui/css/ui-lightness/jquery-ui-1.10.3.custom.min.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="jquery-ui/js/jquery-ui-1.10.3.custom.min.js"></script>
<script type="text/javascript" src="answer.js"></script>
<title>jQuery Test</title>
</head>
<body>
<div>
<h1>My Shopping List</h1>
Add Item | Load List | Clear List
<ul id="my_list">
<li>Brand New Shoes x</li>
</ul>
</div>
</body>
</html>

Offering a few updates that I think might help:
Working Example: https://jsfiddle.net/Twisty/5g72nncw/
$(document).ready(function() {
///////// REMOVE ALL ////////////
$(document).on("click", "div a:nth-of-type(3)", function(e) {
e.preventDefault();
remove_all();
});
$("div a:nth-of-type(3)").click(remove_all);
///////// ADD ITEM ////////////
$(document).on("click", "#add_item", function(e) {
e.preventDefault();
console.log("Running Add Item.");
add_item();
});
$("#add_item").click(add_item);
///////// LOAD ALL ////////////
$(document).on("click", "div a:nth-of-type(2)", function(e) {
e.preventDefault();
load_all();
});
///////// REMOVE ITEM ////////////
$(document).on("click", "#my_list a", function(e) {
e.preventDefault();
var current_item = $(this).parent("li");
remove_item(current_item);
});
//$("#my_list a").click(remove_item(current_item));
///////// EDITABLE ITEM ////////////
});
/// CRUD FUNCTIONS ////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
function add_item() {
if ($("#dialog-form").length == 0) {
console.log("Dialog not found, creating new Dialog.");
var newDialog = $("<div>", {
id: "dialog-form"
});
} else {
console.log("Dialog Found.");
var newDialog = $("#dialog-form");
newDialog.dialog("open");
return true;
}
newDialog.append("<label style='display: block;'>Add your item:</label><input type='text' id='new_item' />");
//$('body').append('<div id="dialog-form"><form> Add your item:<br><input type="text" name="new_item" id="new_item" ></form></div>');
// JQUERY UI DIALOG
newDialog.dialog({
resizable: false,
title: 'Add new item',
height: 240,
width: 260,
modal: true,
autoOpen: false,
buttons: [{
text: "Yes",
click: function() {
var test = $('#new_item').val();
console.log(test);
$("#my_list").append("<li>" + test + " <a href='#'>x</a></li>");
$(this).dialog("close");
$('#new_item').val("");
}
}, {
text: "Cancel",
click: function() {
$(this).dialog("close");
$('#new_item').val("");
}
}]
});
//$("body").append(newDialog);
newDialog.dialog("open");
}
function remove_all() {
$('#my_list li').remove();
}
function load_all() {
$.getJSON("myLists/myList.json", function(json) {
var items = json;
$('#my_list li').remove();
$.each(items, function(index, the_item) {
$('#my_list').append('<li>' + the_item + 'x</li>')
});
});
}
function remove_item(current_item) {
// APPEND DIALOG BOX DIV
$('<div id="dialog-confirm">').appendTo('body');
// JQUERY UI DIALOG
$("#dialog-confirm").dialog({
resizable: false,
title: 'Remove this item?',
height: 140,
width: 260,
modal: true,
buttons: {
"Yes": function() {
$(current_item).hide();
$(this).dialog("close");
},
Cancel: function() {
$(this).dialog("close");
}
}
});
}
When removing an item, you want to pass the <li> to your function. This way it is removed from the <ul>.
When adding the item, I did not append the <div> to the body. I noticed when you appended the <div>, since it was not in the DOM when the page loaded, it does not get initialized as a .dialog() and thus is rendered into the HTML. My method avoids this.
Nothing wrong with the way you create the buttons, yet this is more specific and is how it is described by the UI API: http://api.jqueryui.com/dialog/#option-buttons
Hope this helps.

Related

How to pass parameters to the jquery alert function

I have html table with a delete button. I want to delete the row on button click. For this purpose, when I click a button with class '.btn-danger' which will open a JQuery alert window. My problem is how to pass the $(this) of button click to the $.alert Yes function, so I can remove that row. I have my code below.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.1.0/jquery-confirm.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.1.0/jquery-confirm.min.js"></script>
$(document).ready(function() {
$('.btn-danger').on('click', function(e){
e.preventDefault();
var me = $(this);
var id = $(this).closest('tr').attr('id');
$.alert({
title: 'Alert!',
content: 'Are you sure you want to delete data?',
buttons: {
Yes: function (me) {
//pass value
},
No: function () {
//close function
}
}
});
});
});
Remove me from Yes: function (me) {} because you have already declared it. Then you can call it like below.
Yes: function() {
console.log(me)
},
$('.btn-danger').on('click', function(e) {
e.preventDefault();
var me = $(this);
var id = $(this).closest('tr').attr('id');
$.alert({
title: 'Alert!',
content: 'Are you sure you want to delete data?',
buttons: {
Yes: function() {
console.log(me)
//$("tr#" + id).remove() <--- example of removing the row
},
No: function() {
//close function
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.1.0/jquery-confirm.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.1.0/jquery-confirm.min.css" rel="stylesheet" />
<button class="btn btn-danger">delete</button>
You can try something like this code (If I correct understand you issue)
$(document).ready(function() {
$('.btn-danger').on('click', function(e){
e.preventDefault();
var me = $(this);
$.alert({
title: 'Alert!',
content: 'Are you sure you want to delete data?',
buttons: {
Yes: function () {
me.closest('tr').remove();
},
No: function () {
//close function
}
}
});
});
});
jsfiddle example

JQuery UI Dialog not closing when launched from Input focus event

I have a problem using JQuery and JQuery UI. I have moved to the latest stable version in case that was the issue but I have determined that it isn't.
I am using Chrome
When I use the dialog I created by clicking the element it works without a problem. You can open it and close it mutiple times.
When I use the dialog by clicking the input box (I use the focus event). It opens but it will never close. It dissapears from the screen but the screen remains in modal. If I call the dialog isOpen function I still get true.
I can't find any documentation on this. Can anyone explain the difference in behaviour?
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.css">
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<script>
function RepetitionIntervalInput_display(str, title, okfn, cancelfn) {
$( "#RepetitionIntervalInput_dlg" ).dialog( "open" );
};
$(document).ready(function() {
var ret = "<div id=\"RepetitionIntervalInput_dlg\" title=\"Input Repetition Interval\">";
ret += "</div>";
$("body").append(ret);
$( "#RepetitionIntervalInput_dlg" ).dialog({
autoOpen: false,
width: 500,
modal: true
});
$(document).on('click.tab_stateset', "a[href$='#tab_stateset_delete']", function(event) {
RepetitionIntervalInput_display(
"STRING",
"TITLE",
function () {
console.log("OK");
},
function () {
console.log("CANC");
}
);
event.preventDefault();
});
$(document).on('focus.tab_stateedit', ".tab_stateedit_repetitioninterval", function() {
RepetitionIntervalInput_display(
"STRING",
"TITLE",
function () {
console.log("OK");
},
function () {
console.log("CANC");
}
);
});
});
</script>
</head>
<body>
<h1>A</h1>
aaa
<input type="text" value="NULL" class="tab_stateedit_repetitioninterval"></input>
</body>
</html>
You had a problem with the focus event, which is called twice (on the first click, and once the dialog was closed) and therefore your dialog's "open" was triggered twice.
The fix was to use click on the input instead of focus.
Here is a your snippet with the fix:
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.css">
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<script>
function RepetitionIntervalInput_display(str, title, okfn, cancelfn) {
$( "#RepetitionIntervalInput_dlg" ).dialog( "open" );
};
$(document).ready(function() {
var ret = "<div id=\"RepetitionIntervalInput_dlg\" title=\"Input Repetition Interval\">";
ret += "</div>";
$("body").append(ret);
$( "#RepetitionIntervalInput_dlg" ).dialog({
autoOpen: false,
width: 500,
modal: true
});
$(document).on('click', "a[href$='#tab_stateset_delete']", function(event) {
RepetitionIntervalInput_display(
"STRING",
"TITLE",
function () {
console.log("OK");
},
function () {
console.log("CANC");
}
);
event.preventDefault();
});
$(document).on('click', ".tab_stateedit_repetitioninterval", function() {
RepetitionIntervalInput_display(
"STRING",
"TITLE",
function () {
console.log("OK");
},
function () {
console.log("CANC");
}
);
});
});
</script>
</head>
<body>
<h1>A</h1>
aaa
<input type="text" value="NULL" class="tab_stateedit_repetitioninterval"></input>
</body>
</html>

How to pass back modal dialog confirmation result to calling function?

I've added a jquery UI dialog to an mvc page. After the dialog is opened I need to catch the bool values if the dialog is dismissed or confirmed.
So far I have tried to add a call back as mentioned in another answer, but I'm not sure how to pass that value back to the $('#escalation').on('click', '.delete', function (evt) so that I may perform a redirect if true.
Question:
How can I pass back a bool value to calling function from Jquery UI modal dialog?
Pseudo code:
This is my intended flow of execution for the below fuctions:
1.Call dialog open on a button click. - (working)
2.Pass back true or false depending on if the user selected 'ok' or 'cancel' in the modal dialog.
3.Close the dialog if the returned result to the button click event is false. Otherwise call window.location.href = RedirectTo; code.
Code:
Dialog markup -
<div id="dialog-confirm" title="Delete Selected Record?">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>This record will be permanently deleted.</p> <p>Are you sure?</p>
</div>
Jquery scripts -
<script>
var baseUri = '#Url.Content("~")';
$(document).ready(function () {
$('#escalation').DataTable({
"order": [[6, "desc"]]
});
$('#escalation').on('click', '.delete', function (evt) {
var cell = $(evt.target).closest("tr").children().first();
var EscalationID = cell.text();
var RedirectTo = baseUri + "/EscalationHistory/DeleteEscalation?EscalationID=" + EscalationID;
////open dialog
evt.preventDefault();
$("#dialog-confirm").dialog("open");
//Need to call this code if the dialog result callback equals true
window.location.href = RedirectTo;
//Otherwise do nothing..close dialog
});
//Dialog opened here, not sure how to pass back the boolean values
//to the delete click function above
$("#dialog-confirm").dialog({
autoOpen: false,
modal: true,
buttons: {
"Confirm": function () {
callback(true);
},
"Cancel": function () {
$(this).dialog("close");
callback(false);
}
}
});
});
</script>
Just write your target code inside button click handler or set a flag and use $(".selector").on("dialogclose", function(event, ui) {}); event handler to check the flag state.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/jquery-ui.min.css">
<script src="js/jquery.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script>
$(function() {
var baseUri = "http://localost";
$("#dialog-confirm").dialog({
autoOpen: false,
modal: true,
resizable: false,
width: 450,
open: function() {
$(this).data("state", "");
},
buttons: {
"OK": function() {
$(this).data("state", "confirmed").dialog("close");
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
$(".btn").click(function() {
var escalationId = $(this).data("escalation-id");
var redirectTo = baseUri + "/EscalationHistory/DeleteEscalation?EscalationID=" + escalationId;
// Use "bind" instead "on" if jQuery < 1.7
$("#dialog-confirm").dialog("open").on("dialogclose", function(event, ui) {
if ($(this).data("state") == "confirmed") {
location.replace(redirectTo);
}
});
});
});
</script>
</head>
<body>
<button class="btn" data-escalation-id="123">Delete 123</button>
<button class="btn" data-escalation-id="124">Delete 124</button>
<div id="dialog-confirm" style="display:none">Are you sure?</div>
</body>
</html>
But, IMO, logically better to write the code directly in button click handler.

how to append more than one button with different id to a div by creating a single function

My task is to append button dynamically to a div .. and i want to apppend more than one button with different id to a single or different div by using a simple function. the below code that i have to used to append single button to a div..
<script type="text/javascript">
$(document).ready(function () {
addInputTo($(".myClass"));
$("#field").click(function () {
alert("hi");
$(".myClass").appendTo({
icons: {
primary: "ui-icon-locked"
},
});
});
});
function addInputTo(container) {
var inputToAdd = $("<input/>", {
type: "button",
id: "field",
value: "Test Button"
});
// var s="trype='button";
container.append(inputToAdd);
}
</script>
<div class="myClass"></div>
Is there any solution to append more than one button by creating single function like..
_app.CreateButton (id, text, primaryIcon, secondaryIcon, className);
please help me
and we use the below code to append icon to button but it dosen't work please help me
<script type="text/javascript">
function runEffect() {
debugger;
alert("1");
$( ".AdvSearchSaveButton" ).button({
icons: {
primary: "ui-icon-locked"
},
});
}
$(document).ready(function () {
$("#filed").click(function () {
alert("hi");
runEffect();
// $( "#filed" ).addClass( "ui-icon-locked" );
});
});
</script>
you can change the function addInputTo to
function addInputTo(container, id, text){
var inputToAdd = $("<input/>", { type: "button", id: id, value: text });
container.append(inputToAdd);
}
then call it using
addInputTo($(".myClass"), 'filed', 'test button');
This is really all you need. I just tied the event handler to the click of any <div> with the class = "myClass" with a self calling function.
HTML:
<div class="myClass" style="width:150px; height:150px;background-color:red;"></div>
Javascript:
var id=0;
$(function(){
$(".myClass").click(function(){
id++;
var newButton = "<input type='button' id='number" + id.toString() + "'value='test button'></input>";
$(this).append(newButton);
});
});
Just click on your <div> and a new button with a unique id will be appended to the <div>. Cheers!

jquery dialog with issue after ajax call

I have a page that call from ajax a form with a specific target. this form has a delete entry and for that a warning with a jQuery dialog is used. everything works great.
BUT :
After doing the change or even not doing it, when I open another form (different form by ajax call) and I call the same code below described. When It is submit the dialog the #var_blabla as a value of 1 (the value of the first dialog opened/loaded) and for that moment should be '2'.
I try to figure it out.. So my problem I guess is not for the dialog it self, since I try to load a second page without the constructor and the dialog didn't open (what should be expected).
The problem is on the button 'Submit Delete' that has an event function and it stays active over another that is created.
The site have a lot of forms and many dialogs for each form, is there a wait to unbind, or destroy completely the dialog and the buttons? Ideas please?
Thanks
simplified 1st dialog call code:
$("#dialog-confirm-elimina").dialog({
autoOpen: false,
resizable: false,
height:220,
modal: true,
buttons: {
'Submit Delete': function() { $('#var_blabla').val('1');
$('#form_submit').submit();
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
simplified 2nd dialog call code:
$("#dialog-confirm-elimina").dialog({
autoOpen: false,
resizable: false,
height:220,
modal: true,
buttons: {
'Submit Delete': function() { $('#var_blabla').val('2');
$('#form_submit').submit();
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
UPDATE:
<script type="text/javascript">
submited=false;
var toggleOpened = true;
$("#admin_retractil_1").click(function () {
if(!toggleOpened){
$('#admin_retractil_1').toggleClass('toggleGESBHeadown');
toggleOpened=true;
}
else{
$('#admin_retractil_1').toggleClass('toggleGESBHeadown');
toggleOpened=false;
}
var objecto = $(this).attr("id");
$('#' + objecto+"_div").slideToggle("slow");
});
var toggleOpened2 = false;
$("#admin_retractil_2").click(function () {
if(!toggleOpened2){
$('#admin_retractil_2').toggleClass('toggleGESAHeadown');
toggleOpened2=true;
}
else{
$('#admin_retractil_2').toggleClass('toggleGESAHeadown');
toggleOpened2=false;
}
var objecto = $(this).attr("id");
$('#' + objecto+"_div").slideToggle("slow");
});
$(document).ready(function() {
//$( "button").button();
var locked = true;
$( "#EditDataForm").button({ icons: { primary: "ui-icon-locked" }});
$( "#EditDataForm" ).click(function() {
if(locked){
locked = false;
$( "#EditDataForm").button({ icons: { primary: "ui-icon-unlocked" }});
$('#edit_data_admin').slideToggle("slow");
$('#view_data_admin').slideToggle("slow");
}else{
locked = true;
$( "#EditDataForm").button({ icons: { primary: "ui-icon-locked" }});
$('#edit_data_admin').slideToggle("slow");
$('#view_data_admin').slideToggle("slow");
}
return false; });
$( "#DelDataForm").button({ icons: { primary: "ui-icon-scissors" }});
$( "#DelDataForm" ).click(function() {
$('#dialog-confirm-del').dialog('open');
return false; });
/*abre popup de alerta de eliminar */
arrayRemove.push("dialog-confirm-del");
$("#dialog-confirm-del").dialog({
autoOpen: false,
resizable: false,
height:220,
modal: true,
buttons: {
'Remove Stuff': function() {
$('#sel_action_form').val('TypoDesClients_DelDef');
$('#name').val('_____');
$('#form_submit').submit();
$(this).dialog('close');
},
Cancelar: function() {
$(this).dialog('close');
}
}
});
$( "#AcceptChanges").button({ icons: { primary: "ui-icon-check" }});
$("#form_submeter").validator({
position: 'center right',
offset: [0, 0],
message: '<div><em /></div>'
}).bind("onSuccess", function(e, els) {
var numSucceeded = els.length,
numExpected = $(this).data('validator').getInputs().length;
if (numSucceeded === numExpected) {
if(!submited){submited=true;
SubmitFormSV('form_submit', 'action/action_a.php');
return false;
}else return false;
}
});
$( "#radio" ).buttonset();
$("#1_radio").click(function () {
$("#tr_1").show();
});
$("#2_radio").click(function () {
$("#tr_1").hide();
});
});
local lib:
function SubmitFormSV(formul, address)
{
DoChecks();
$("#loading").show("slow");
$.post(baseURL + address, $('#' + formul).serialize(), function(html){
$('#content').slideUp("slow", function () {
AjaxChargePage(html, true);
});
});
$("#loading").hide("slow");
return false;
}
next the next chuck of javascript is similar to this one.
and with this work because destroy didn't:
DoChecks() As:
$.each(arrayRemove, function() {
var element = arrayRemove.pop();
$('#'+element).remove();
});
When you're done with dialog 1 try...
$("#dialog-confirm-elimina").dialog("destroy");
or in your Cancel function...
$(this).dialog("destroy");
The .dialog command creates a new dialog on the element selected. You're doing this twice, and thus having problems. Once the dialog is created it can be reused using open and close methods or destroyed as I've shown above and then recreated.
Ok, then finally I got a solution that make everything works. Instead of using the
$("#dialog-confirm-elimina").dialog("destroy");
I use:
$("#dialog-confirm-elimina").remove();
I still don't know the reason but clearly don't have the problem anymore.
Thanks for the answer though.
PS: If anyone know how could this append I appreciate to illuminate me about it.Thanks

Categories