How to put buttons in a html page in a jQuery dialog - javascript

eHello everyone,the following is my code to display a jquery dialog window with a closing button "OK":
<script type="text/javascript">
$(function(){
$("#dialog").dialog({
autoOpen:false,
bgiframe:true,
buttons: { "OK": function() { $(this).dialog("close"); } },
width:500,
height: 350,
modal: true,
show: 'slide',
hide:'slide',
title:"Similar Trends Detected in 2nd DataSet"
});
$("#userid").focus();
});
function showForm(matches){
$("#dialog").html(matches).dialog("open");
}
Currently it runs by supplying a string variable "matches",then the content of the variable gets displayed on the dialog frame.
Now me and my teammate want to extend this dialog a little,we want to attach a button to every line inside the html content("matches" variable),please note that we don't want buttons in the dialog(like another "OK" button),but we want buttons "inside" the frame (the actual html content).
So I would like some help here,how could I modify my "matches" variable,to have buttons also shown inside the dialog.
Thanks.

EDIT: Updated based on comments from OP
function showForm(matches){
// Of course, you'll need to modify with your own button.
// I also added a valid <br>, assuming you want it there.
matches = matches.replace( /<\/br>/g, '<button>my button</button><br>' );
$("#dialog").html( matches ).dialog("open"); // Insert new HTML content
}
Does the matches variable contain HTML?
You could just make a jQuery object out of it, and traverse it like any other HTML:
function showForm(matches){
// Of course, you'll need to modify with your own button.
// I also added a valid <br>, assuming you want it there.
matches = matches.replace( /<\/br>/g, '<button>my button</button><br>' );
$("#dialog").html( matches ).dialog("open"); // Insert new HTML content
}
Relevant jQuery docs:
.after() - http://api.jquery.com/after/
.find() - http://api.jquery.com/find/
Traversing: http://api.jquery.com/category/traversing/

what do you mean by every line? can you post a sample value for the matches variable? why not just include the buttons in the matches string value?
anyway, you can also provide a callback function to the dialog widget's 'open' event.
$("#dialog").dialog({
autoOpen:false,
bgiframe:true,
buttons: {
"OK": function() {
$(this).dialog("close");
}
},
width:500,
height: 350,
modal: true,
show: 'slide',
hide:'slide',
title:"Similar Trends Detected in 2nd DataSet",
open: function() {
var targetElements = 'br';
$(this).find(targetElements).after('<button>click me</button>');
}
});
after every br tag in the content, a button will be appended after it... every time the dialog is shown, the open callback will be triggered.

So the matches content is some static set of HTML. Once it has been added to the DOM you can use the same selectors and controls you use for everything else. So let us assume for the moment that the matches field contains a list of elements.
function showForm(matches){
$("#dialog").html(matches).dialog("open");
var b = $("<input type='button' value='clickme'/>");
$("#dialog ul li").append(b);
}
Of course this is only really going to work if you have some conception of what match contains. If you know for example that it is a set of divs with a certain class that will help in making the selector.

Related

Can't find element using UI hash in Marionette Layout

I'm not sure why I can't get the button element using my UI hash. This is what my Layout looks like:
Layout: App.Base.Objects.BaseLayout.extend({
// Rest of the code left out for brevity
ui: {
btnSave: "#btnSave"
},
events: {
"click #ui.btnSave": "onSave"
},
onInitialize: function () {
this.listenTo(App.vent, "DisableSaveButton", function(val) {
this.disableSaveButton(val);
},this);
},
disableSaveButton: function () {
this.ui.btnSave.prop("disabled",val).toggleClass("ui-state-disabled",val);
},
onSave: function () {
alert("saved!");
}
})
In VS2013, when my breakpoint hits the line inside disableSaveButton method, I entered $("#btnSave") into the Watch window and I was able to get the element back. I could tell because it had a length of 1. From this, I know the button is rendered. However, if I enter this.ui.btnSave into the Watch window, I would get an element with length of 0.
My BaseLayout object is basically a custom object extended from Marionette.Layout
Marionette version: 1.8.8
Any ideas why I can't find the button element using this.ui.btnSave?
Thanks in advance!
Got some help from a coworker and the issue might be because the element is out of scope. Basically, inside the Layout object, 'this' does not contain the element. We were able replace 'this.ui.btnSave' with '$("#btnSave",this.buttonset.el)' and that works fine. buttonset is the region that actually contains the html element.
This seems like an inconsistency because even though the ui hash didn't work, the click event utilizing the ui hash did work.
UPDATE 6/3/2015:
Another coworker of mine provided a better solution. Basically, in my Layout I use a display function to display my view. It looks something like this:
Layout: App.Base.Objects.BaseLayout.extend({
// Rest of the code left out for brevity
display: function() {
$(this.buttonset.el).html(_.template($("#buttonset-view").html(), {"viewType": viewType}));
}
})
Basically, I'm saying to set the html of my region, which is this.buttonset.el, to my template's html. As of now, my layout doesn't know any of the elements inside the region. It just contains a region which displays the elements. So there is some sort of disconnect between my layout and the elements in my region.
The correct solution, as opposed to my earlier workaround, is to simply add the following line of code at the end:
this.bindUIElements();
From Marionette Annotated Source:
This method binds the elements specified in the “ui” hash inside the
view’s code with the associated jQuery selectors.
So this final code looks like this:
Layout: App.Base.Objects.BaseLayout.extend({
// Rest of the code left out for brevity
display: function() {
$(this.buttonset.el).html(_.template($("#buttonset-view").html(), {"viewType": viewType}));
this.bindUIElements();
}
})
With this, I was able to finally able to retrieve my element using this.ui.btnSave.

jQuery UI MultiSelect Widget-Cant able to apply in one item

I'm using this jQuery UI Multiselect Widget script: http://runnable.com/UgMdJqspu4chAAAP/how-to-create-jquery-ui-multiselect-widget in asp.net.I have one child page with master page.While i am applying this control by default its applying to all dropdownlist.I want to apply for a single Dropdownlist. Can anybody help me out?
<script type="text/javascript">
$(function () {
/*
define global variable,
and store message container element.
*/
var warning = $(".message");
$('select').multiselect(
{
/*
The name of the effect to use when the menu opens.
To control the speed as well, pass in an array
*/
show: ["slide", 1000],
/*
The name of the effect to use when the menu closes.
To control the speed as well, pass in an array
*/
hide: ["slide", 1000],
/*
Either a boolean value denoting whether or not to display the header,
or a string value.
If you pass a string,
the default "check all", "uncheck all", and "close"
links will be replaced with the specified text.
*/
header: "Choose only TEN items!",
/*
Fires when a checkbox is checked or unchecked,
we are using this option to restrict,
user to select no more than 3 option
*/
click: function (e) {
if ($(this).multiselect("widget").find("input:checked").length > 10) {
warning.addClass("error").removeClass("success").html("You can only check three checkboxes!");
return false;
}
else {
warning.addClass("success").removeClass("error").html("Check a few boxes.");
}
}
/*
.multiselectfilter()
Initialize filtering on any of your multiselects
by calling multiselectfilter() on the widget.
*/
}).multiselectfilter();
});
</script>
In $('select').multiselect() while i am passing my dropdown-list Id then this control is not working.Only its working while giving 'select'and simultaneously its applying to all dropdown-list. but i want to apply in one dropdown-list.Can anyone suggest me?
With ID it should work
$(document).ready(function(){
$("#example").multiselect();
});
Reference link below is using the same plugin, Can you check your browser console for any javascript errors ?
http://www.erichynds.com/blog/jquery-ui-multiselect-widget

Show and hide dynamic jQuery UI Dialogs

I know this should be simple, but it doesn't appear to be working the way I hoped it would.
I'm trying to dynamically generate jQuery UI dialogs for element "help."
I want to toggle the visibility of the dialog on close (x button in dialog), and clicking of the help icon. This way, a user should be able to bring up the dialog and get rid of it, as needed, multiple times during a page view.
// On creation of page, run the following to create dialogs for help
// (inside a function called from document.ready())
$("div.tooltip").each(function (index, Element) {
$(Element).dialog({
autoOpen: false,
title: $(Element).attr("title"),
dialogClass: 'tooltip-dialog'
});
});
$("a.help").live("click", function (event) {
var helpDiv = "div#" + $(this).closest("span.help").attr("id");
var dialogState = $(helpDiv).dialog("isOpen");
// If open, close. If closed, open.
dialogState ? $(helpDiv).dialog('close') : $(helpDiv).dialog('open');
});
Edit: Updated code to current version. Still having an issue with value of dialogState and dialog('open')/dialog('close').
I can get a true/false value from $(Element).dialog("isOpen") within the each. When I try to find the element later (using a slightly different selector), I appear to be unable to successfully call $(helpDiv).dialog("isOpen"). This returns [] instead of true/false. Any thoughts as to what I'm doing wrong? I've been at this for about a day and a half at this point...
Maybe replace the line declaring dialogState with var dialogState = ! $(helpDiv).dialog( "isOpen" );.
Explanation: $(helpDiv).dialog( "option", "hide" ) does not test if the dialog is open. It gets the type of effect that will be used when the dialog is closed. To test if the dialog is open, you should use $(helpDiv).dialog( "isOpen" ). For more details, see http://jqueryui.com/demos/dialog/#options and http://jqueryui.com/demos/dialog/#methods.
I was able to get it working using the following code:
$("div.tooltip").each(function (index, Element) {
var helpDivId = '#d' + $(Element).attr('id').substr(1);
var helpDiv = $(helpDivId).first();
$(Element).dialog({
autoOpen: true,
title: $(Element).attr("title"),
dialogClass: 'tooltip-dialog'
});
});
// Show or hide the help tooltip when the user clicks on the balloon
$("a.help").live("click", function (event) {
var helpDivId = '#d' + $(this).closest('span.help').attr('id').substr(1);
var helpDiv = $(helpDivId).first();
var dialogState = helpDiv.dialog('isOpen');
dialogState ? helpDiv.dialog('close') : helpDiv.dialog('open');
});
I changed the selectors so that they're identical, instead of just selecting the same element. I also broke out the Id, div and state into separate variables.

Custom alert using Javascript

How can I create a custom alert function in Javascript?
You can override the existing alert function, which exists on the window object:
window.alert = function (message) {
// Do something with message
};
This is the solution I came up with. I wrote a generic function to create a jQueryUI dialog. If you wanted, you could override the default alert function using Matt's suggestion: window.alert = alert2;
// Generic self-contained jQueryUI alternative to
// the browser's default JavaScript alert method.
// The only prerequisite is to include jQuery & jQueryUI
// This method automatically creates/destroys the container div
// params:
// message = message to display
// title = the title to display on the alert
// buttonText = the text to display on the button which closes the alert
function alert2(message, title, buttonText) {
buttonText = (buttonText == undefined) ? "Ok" : buttonText;
title = (title == undefined) ? "The page says:" : title;
var div = $('<div>');
div.html(message);
div.attr('title', title);
div.dialog({
autoOpen: true,
modal: true,
draggable: false,
resizable: false,
buttons: [{
text: buttonText,
click: function () {
$(this).dialog("close");
div.remove();
}
}]
});
}
Technically you can change what the alert function does. But, you cannot change the title or other behavior of the modal window launched by the native alert function (besides the text/content).
If you're looking for a javascript/html/css replacement, I recommend checking out jQueryUI and its implementation of modal dialogs.
"override" way is not good enough, suggest you to create a custom popup box. The best benefit of this solution is that you can control every details.
No, you can not using the default alert.
Not even formating.
But, I recomend you using Sweet alert to do that.

Combining multiple jQuery functions

Is there any way to combine all of this to reduce the amount of js? This is just an example of some of the jquery dialogs I have in my site, there are a few more too. Thanks.
//initiate Search refinement dialog here
$("#chooseMoreCnt, #chooseMoreCat, #chooseMorePr").dialog({
bgiframe: true,
autoOpen: false,
width: 500,
modal: true,
open: function(type, data) {
$(this).parent().appendTo(jQuery("form:first"));
}
});
//trigger country dialog
$('a.chooseMoreCnt').click(function() {
$('#chooseMoreCnt').dialog('open');
return false;
});
//trigger category dialog
$('a.chooseMoreCat').click(function() {
$('#chooseMoreCat').dialog('open');
return false;
});
//trigger price dialog
$('a.chooseMorePr').click(function() {
$('#chooseMorePr').dialog('open');
return false;
});
If your links point to the IDs of the dialog elements, and if you add a meta class choose to each of them, you could combine the last three calls to:
$('a.choose').click(function() {
$(this.hash).dialog('open');
return false;
});
The HTML for one of those links is the most semantically correct and even works with JS disabled (assuming, the dialogs are there, then):
Choose more categories
The this.hash part explained:
this in the context of a jQuery event handling function is always the element, that the event appeared at. In our case, it's the clicked link. Note, that it's the DOM node, not a jQuery element.
this.hash: DOM nodes, that correspond to HTML <a/> elements, have certain special properties, that allow access to the target they're linking to. The hash property is everything after (and including) an # character in the URL. In our case, if the link points to the elements that should become dialogs, it's something like the string "#chooseMoreCnt".
$(this.hash) is the jQuery function called for, e.g., "#chooseMoreCnt", which will select the appropriate div.
For the dialog initialization, I would also go for classes:
$(".choose_dialog").dialog({
bgiframe: true,
autoOpen: false,
width: 500,
modal: true,
open: function(type, data) {
$(this).parent().appendTo(jQuery("form:first"));
}
});
Yes, it means to change the markup, but it also provides you with the freedom to
add any number of dialogs lateron
add any number of openers to any dialog lateron
style all dialogs and links to dialogs consistantly with minimal CSS
without touching the Javascript anymore.
If the dialogs are initiated differently (as mentioned in the comments), then you could go for this part with CuSS's $.each() approach and read the appropriate width inside the function from an object defined elsewhere:
var dialog_widths = {'chooseMoreCat': 400, 'chooseMorePr': 300, /*...*/ };
This is what I would suggest. Specify a general DialogContent (say) class to all the divs and initialize them using:
$(".dialogContent").dialog({
bgiframe: true,
autoOpen: false,
width: 500,
modal: true,
open: function(type, data) {
$(this).parent().appendTo(jQuery("form:first"));
}
});
And ofcourse use Boldewyn's solution for click event (it is better to use live() IMHO if things are getting dynamically generated). This way you take care of all initializations and click events with way less code.
HTH
well, this is a little complicated to minimize.
do you have more than 3 dialogs? If yes you can do something like this:
var dialogs=["chooseMorePr","chooseMoreCat","chooseMoreCnt"];
$.each(dialogs,function(i,v){
$('a.'+v).click(function(){$('#'+v).dialog('open');});
});
In order to optimize performance, you should use live when connecting to several elements. Below is my approach to the problem. The solution is dynamic (add as many dialogues as you want to) and very speedy.
Remember to change #anyParentOfTheLinks into the parent div or in worst case remove it and jQuery will use document instead.
var dialogues = ['#chooseMoreCnt', '#chooseMoreCat', '#chooseMorePr'];
$(dialogues.toString()).dialog({
// ...
});
$('a', '#anyParentOfTheLinks').live('click', function(){
// Cache for performance
var $this = $(this), len = dialogues.length;
for(var i = 0; i < len; i++)
if($this.is('.' + dialogues[i].substr(1))) {
$this.dialog('open');
break;
}
return false;
});

Categories

Resources