How can I pass an element to a jQuery UI dialog box? - javascript

Goal
I've got a web page with a table of items. Each item has a delete button beside it. When that button is clicked, I want to
Ask the user to confirm
Delete the corresponding item from the database
Remove that item's row from the list
Current solution
Right now, I'm doing something like this:
$('button.delete').click(function(){
thisRow = $(this).parent();
itemID = $(this).parent().attr('id');
if (confirm('Are you sure?')){
$.post('/manage_items.php', {"action":"delete", "itemid":itemID}, function(){
thisRow.hide("slow").remove();
});
}
}
This solution works because each button.delete can determine which row and item it belongs to, and act accordingly.
Desired solution
Instead of the clunky "OK or Cancel" alert box, I'd like to use a jQuery UI dialog box. But I'm not sure how to let the dialog know which row and item it should handle on any given click.
Here's how you set it up:
1) Define a dialog box div
<div class="dialogbox" id="confirmdeleteitem" title="Really DELETE this item?">
<p>Gee golly, are you s-s-s-sure you want to do that?!</p>
</div>
2) Set up the dialog box behavior
$('#cofirmdeleteitem').dialog({
//other options - not relevant here
buttons: {
"Nevermind": function() {
//do nothing
},
"Alright! Woo!": function(){
//do something
}
}
});
3) Set the click event that will open the dialog
$('button.delete').click(function(){
$('#confirmdeleteitem').dialog('open');
});
In this last step, I'd like to be able to pass some information to the dialog - which delete button was clicked, for example. But I don't see a way to do that.
I could insert a hidden dialog div.dialog into each item row up front, or insert one into a particular row after its button is clicked. Then the $(this).parent() references would grab the correct row...
Is there an easier way to do this?

i do something like this:
function ConfirmationDialog(title, question, options) {
var d = $('<div title="' + title + '"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>' + question + '</p></div>');
d.dialog({
bgiframe: true,
resizable: false,
height: 190,
width: 350,
modal: true,
overlay: {
backgroundColor: '#000',
opacity: 0.5
},
buttons: options
});
}
and then call my function from the click event.

It ended up being most straightforward to set up the dialog behavior inside the click function itself. Actually, it's not much different than my original example.
$('button.delete').click(function(){
thisRow = $(this).parent().parent();
thisRow.css("background-color","red");
skuid = $(this).parent().parent('tr').attr('id').substr(5);
$('#dialogbox').dialog({
autoOpen: false,
modal: true,
draggable: true,
width: 600,
buttons: {
"Actually, I can just mark it inactive": function() {
thisRow.css("background-color","inherit");
$(this).dialog("close");
},
"This SKU needs to be deleted": function() {
$.post('/intranet/backstage/modify_sku_info.php', {"action":"delete", "skuid":skuid}, function(result){
thisRow.hide("slow").remove();
});
$(this).dialog("close");
}
}
});
$('#dialogbox').dialog('open');
return false;
});
Since div#dialogbox doesn't get hidden until $('#dialogbox').dialog() is called, I just gave it an inline style of display:none.
If I end up needing something that can be generalized, as hyun suggested, I'll revisit the issue.

You could store the row in a global variable, like this:
var deletingId;
$('button.delete').click(function() {
deletingId = $(this).parent().attr('id');
$('#confirmdeleteitem').dialog('open');
});
$('#confirmdeleteitem').dialog({
//other options - not relevant here
buttons: {
"Never mind": function() { },
"Alright! Woo!": function(){
$.post(
'/manage_items.php',
{ action: "delete", itemid: deletingId },
function() {
$('#' + deletingId).hide("slow").remove();
}
);
}
}
});
This will only work if the dialog is modal; otherwise, the user could click two different delete links, and you'd need multiple dialogs.

Why can't you just call a setup method to build the dialog as you see fit?
setupMyDialog( '#confirmdeleteitem', info1, info2 );
$('#confirmdeleteitem').dialog...
Alternatively, just store the information in global space before you show the dialog. Remember that your javascript variables can have global scope, or you can store information arbitrarily on objects/functions (which are just objects).
myDataStore = {};
myDataStore.row = foo;
myDataStore.col = bar;

You could add the "rel" attribute to the dialog and store it there, instead. That way you don't need to worry about global variables, and it's semantically not-too-bad, since you are defining a relationship between the dialog and a row. So it'd just be $('#confirmdeleteitem').attr('rel', $(this).parent().attr('id').dialog('open');

Related

How to save the user input data from a dialog box into a hidden field: Jquery and HTML

I have been working on this button that opens a dialog box containing an option-selecting table when clicked on. The thing is, I want the data input by the customer to be saved in a hidden field.
I have tried targeting the speicific field with getElementById, but I have no idea how to check whether or not it worked.
$(function() {
$("#opener").click(function() {
($("#table").dialog("isOpen") == false) ? $("#table").dialog("open") : $("#table").dialog("close") ;
});
$("#table").dialog({
autoOpen: false,
width: 300,
height: 250,
position: ['center',100],
buttons: {
Abbrechen: function() {
$(this).dialog("close");
},
Fertig: function() {
$('input[name="hfield"').val($("#safety_gear_select").val());
$(this).dialog("close");
}
},
});
Does anyone know how can I achieve this? TIA
I found a solution, hopefully it will help someone else too.
This is what I added to my button's code, where 'hfield1' is the name of the hidden field I want the data saved in and the #safety_gear_select is the id of the select field containing the input I wanna save in the hidden field.
It displays the name of the choice in the console rather than the index number, but that can easily be achieved too by replacing .html() with .val()
Fertig: function() {
$('input[name="hfield1"').val($("#safety_gear_select option:selected").html());
$('input[name="hfield2"').val($("#pawl_device_select option:selected").html() );
$('input[name="hfield3"').val($("#buffer_select option:selected").html() );
$(this).dialog("close");
}

.html() not working for live update of html table after jquery $.post

I currently have a jQuery dialogue box ( http://api.jqueryui.com/dialog/ ) which when the user clicks on a table with class low_inv_notes, will pop up and allow them to enter in whatever notes they want.
The note gets properly stored in the database, however I am trying to achieve a live update of the table td when they hit submit on that dialogue box, and this is not working. If the user wants to see the updated table they must reload the page which is not something i want.
I believe my problem has something to do with .html(); I have made alerts to check the variables i am using have values and i have checked to make sure all id's and class's are properly labels.
Here is the code for my dialogue box at the moment:
$( ".low_inv_notes" ).click(function(event) {
var notes = $(this).andSelf().html();
var netQty = $(this).closest('tr').find('td:eq(6)').text();
var stockNumber = $(this).closest('tr').find('td:eq(0)').text();
var $dialog = $('<div id="dialog"></div>')
.html('<textarea id="noteContent" style="width: 450px; height: 190px;">' + notes + '</textarea>')
.dialog({ title: 'Edit This Note:',
autoOpen: false,
height: 300,
width: 500,
modal: true,
buttons: {
"Submit":function() {
var old = notes;
var new_notes = $("#noteContent").val();
if(new_notes == old){
alert("Note is the same - change to submit");
$(this).dialog('close');
$(this).dialog('open');
}
else {
$.post( "edit_low_inv_notes.php", { netQty:netQty, stockNumber: stockNumber, new_notes: new_notes},function(data){
var id = stockNumber+'notes';
//alert(id);
//alert(new_notes);
//$('#00260040.01Dnotes').html('test');
$('#'+id).html(new_notes);
}
);
$(this).dialog("destroy").remove();
}
},
"Close":function() {
$(this).dialog("destroy").remove();
}
}
});
$dialog.dialog( "open" );
});
I have tried substituting .text in for .html as well as having .done before the function(data) with the same amount of success. any ideas? Thanks ahead of time
I strongly suspect that the problem is with the . character in the middle of your element id. If your id value really looks like "00260040.01D", then jQuery is going to interpret that . as being a class selector.
You can try this:
$('#' + id.replace(/\./g, '\\.')).html(new_notes);

How to keep Sencha Ext.Msg from closing on button click

So i Have a Message box I built to be able to send a message. It has 2 inputs, and an OK and Cancel buttons. I can access the contents and do the normal logic quite easily how I set it up:
Ext.Msg.show({
title: 'Send a Message: ',
cls: 'MessageBox',
html: '<div class="message-InnerContainer" >' +
'<input type="text" id="messageBoxSubject" placeholder="Subject" class="messageBox-Input"/>' +
'<textarea id="messageBoxMessage" placeholder="Message" class="messageBox-TextArea"></textarea>' +
'<div>',
closable: false,
buttons: [
{ no: 'Cancel', text:'Cancel', cls:'messageBox-CancelButton'},
{ yes: 'OK', text:'Ok', cls:'messageBox-OkButton'}
],
fn: function (btn) {
if (btn == 'ok') {
//do success logic
}
else (){
//do failure logic
}
}
});
There is only one problem: I can't seem to find a way to keep the box from auto closing when OK is pressed. Ideally I would like to run a quick check to ensure that the two inputs are not empty. I think I might just be able to override buttons by placing custom buttons in the html section, but if there is a way to halt the auto closing it would be more syntactically pleasing and readable. Does anyone know if its possible?
Oh my! You should really consider using some regular Ext text field and text area as items of the window instead of your own baked html...
Anyway, use the handler of your buttons, instead of the fn handler. You'll be able to do whatever you want in there, and close the window only if you feel like it:
buttons: [
{ text:'Cancel', cls:'messageBox-CancelButton', handler: function() {
this.hide();
}},
{ text:'Ok', cls:'messageBox-OkButton', handler: function() {
var allGood = false;
// do your stuff here
// ... and if your satisfied with the result, close the window
if (allGood) {
this.hide();
}
}}
]

jQuery.off() is not removing binding

For some reason jQuery.off('click') doesn't seem to be working here. When the 'Yes' button is clicked in the model another model just pops up. What am I doing wrong?
code:
$(function(){
//If there are warnings on the page bind alert
if ($('.renewal-warning').length > 0){
(function (){
$('#signRentalContainer').on('click', '.renewal-warning', function(e){
var buttonHandle = this;
//Prevent submission
e.preventDefault();
//Show warning model
$.modal({
content: $('#renewalWarning').html(),
title: "Order Renewal Warning",
buttons: {
'Yes': function(win) { $(buttonHandle).off('click').click(); },
'No': function(win) { win.closeModal(); }
},
maxWidth: 250,
closeButton: false
});
});
})();
}
});
Pretty sure you're going to need to provide it the same element, as well as the same selector.
$('#signRentalContainer').off('click', '.renewal-warning');
In the .on() handler, this is the '.renewal-warning' element that was clicked, not the #signRentalContainer element.
If there are several of these '.renewal-warning' elements, and you only want to disable one at a time, the simplest way is to change its class so that it no longer matches the selector.
$(this).removeClass('renewal-warning')
.addClass('renewal-warning-disabled');
Because the this refer to the context of the handle function, not the function itself.
Try making it a named function, then refer to it when you call off:
$("body").off("click", '#signRentalContainer', buttonHandle);
BTW, any reason we can't use unbind directly here?
$("#signRentalContainer").unbind("click");

How to update hidden field value when clicking on jQuery Accordion Header?

I am using a hidden field to store the active index for the accordion:
var activeIndex = parseInt($('#ContentPlaceHolder1_hidAccordionIndex').val());
$("#accordion").accordion({
changestart: function () {
var value = $(this).scrollTop();
window.scrollTo(0, value);
},
autoHeight: false,
event: "mousedown",
active: activeIndex,
collapsible: true,
disabled: false,
change: function (event, ui) {
var index = $(this).children('h4').index(ui.newHeader);
$('#ContentPlaceHolder1_hidAccordionIndex').val(index);
}
});
Currently, the hidden field value is set in the codebehind. Therefore, if the user clicks on the accordion header, I would like to update the value of the hidden field according to the header that has been clicked.
Any ideas on how to do this? Thanks in advance.
Use following function for change event handler:
change: function (event, ui) {
var index = $(this).accordion("option", "active");
$('#ContentPlaceHolder1_hidAccordionIndex').val(index);
}
I have made an exact same example as yours in this fiddle and it works like a charm.
The only possible reason for you to not find the index of the current header is that you might have <h3> headers in your markup and your selecting <h4> in your change handler.
Change one or the other and it should normally work.
One way to handle this, is by adding a class called accordionHeader or something to each of the h3s. Then after the initial build of the accordian, call another event handler.
In my example I just performed a bind on h3 for quickly providing a demo.
$("#accordion").accordion();
$('h3').bind('click', function() {
$('#HiddenInputField').val($(this).children('a').html());
alert($('#HiddenInputField').val());
});
Simple working example Fiddle

Categories

Resources