How to create a modal JQuery UI dialog from a Html page fragment fetched by $.get() - jquery-ui

with the below code, I'm able to add a page fragment to an other page. The page contains a form to be posted to a certain action method.
$("#ul-menu a").click(function () {
$.get($(this).attr("href"), function (response) {
$("#dialog-div div").replaceWith($(response));
});
return false;
})
Instead of having the form anywhere in the page, I'd like to get it as a modal JQueryUI dialog.
How can I do that.
Thanks for helping.

This will work for you. Also, I've added a better method of preventing the original click. Instead of returning false, which kills all bubbling, you should use event.preventDefault();
$("#ul-menu a").click(function (event) {
event.preventDefault();
$.get($(this).attr("href"), function (response) {
$(response).dialog({ modal : true });
});
})

You don't even need to insert the response into the page.
You can just do this:
var myDialog = $(response).dialog();
EDIT
Not the above snippet won't create a modal dialog, I assumed you know you need to pass in { modal: true } as part of your configuration.

Related

JQuery UI Autocomplete widget not working on a bootstrap modal

I have a bootstrap modal dialog on which I have a textbox that I want to leverage the functionality of jQuery UI Autocomplete widget. However the autocomplete widget isn't being fired at all. I know this as I placed a breakpoint on the action on my controller that should return the Json to be rendered by the autocomplete textbox. The action is never hit
Out of curiosity that I was doing something wrong, I copy pasted the textbox onto a View and to my dismay, the breakpoint on my action in the controller is hit. I have narrowed this down to the fact that may be the textbox is never wired to use the autocomplete feature once the DOM has loaded.
Here is the textbox on my modal
<input type="text" name="someName" id="autocomplete" data-autocomplete-url="#Url.Action("Autocomplete", "warehouses")" />
Here is the action method that returns the Json
public ActionResult Autocomplete(string term)
{
string[] names = { "Auma", "Dennis", "Derrick", "Dylan", "Mary", "Martha", "Marie", "Milly", "Abel", "Maria", "Bergkamp", "Arsene", "Alex", "Mwaura", "Achieng" };
var filtered = names.Where(a => a.IndexOf(term, StringComparison.OrdinalIgnoreCase) >= 0);
return Json(filtered, JsonRequestBehavior.AllowGet);
}
And here is how I wire up the textbox to use the autocomplete widget
$(document).ready(function () {
$('#autocomplete').autocomplete({
source: $(this).data('autocomplete-url'),
data: {term: $(this).val() }
});
});
I have seen similar questions asked but none of them was due to the action not being hit.
As per the documentation for Bootstrap 3, they expose a set of events that you can hook into with most of their JS features.
In this case the events are:
show, shown, hide, hidden and loaded
The following code will initialize your autocomplete input field after the modal has been shown. (replace myModal with the id of the modal you are going to show)
$(document).ready(function () {
$('#myModal').on('shown.bs.modal', function (e) {
$("#autocomplete').autocomplete('destroy'); //remove autocompete to reattach
$('#autocomplete').autocomplete({
source: $(this).data('autocomplete-url'),
data: {term: $(this).val() }
});
});
});
If you are fetching a partial that contains the input field and appending it to the modal during the toggle, it will be better to do this initialization in the callback from that ajax request.

JQuery-ui Tabs - reload page with completely new content not working

I'm loading in a report and displaying it with jquery-ui in tab format. The report is returned by an ajax call in json, and a function is formatting it into HTML. Example code below:
<div id="reportdiv">
</div>
<script>
function displayreport(objectid)
{
$( "#reportdiv" ).hide();
$( "#reportdiv" ).html("");
$.ajax({
type: "GET",
headers: { 'authtoken': getToken() },
url:'/reportservice/v1/report/'+objectid.id,
success: function(data){
if(data == null)
{
alert("That report does not exist.");
}
else
{
var retHTML = dataToTabHTML(data.config);
$("#reportdiv").html(retHTML).fadeIn(500);
$(function() {
tabs = $( "#reportdiv" ).tabs();
tabs.find( ".ui-tabs-nav" ).sortable({
axis: "x",
stop: function() {
tabs.tabs( "refresh" );
}
});
});
}
}
});
}
</script>
This works fine the first time displayreport is called. However, if the user enters another value and runs displayreport again, the "tabs" format is completely lost (the tabs are displayed as links above my sections, and clicking on a link takes you to that section further down the page).
I figured completely re-setting the reportdiv html at the beginning of the function would bring me back to original state and allow it to work normally every time. Any suggestions?
After more testing, found that destroy was the way to go. If I've set up tabs already, run the destroy, otherwise, skip the destroy (http://jsfiddle.net/scmxyras/1/) :
if(tabs!=undefined)$( "#reportdiv" ).tabs("destroy");

Zend Framework 2 - jquery modal popup issue

I have a view showform.phtml that is loaded into a div via jquery dialog. In the view I am loading a javascript with a $(form).submit() listener. The problem is, the javascript is never loaded. I have tried a couple of different methods, including $this->headScript()->appendScript(script), $this->headScript()->appendScript(file). I even tried just including the script in the layout and index view so that it was sure to be available... but the popup never fires it.
I suspect it has something to do with the fact that I am using setTerminal(true) on the form view... but I don't know what the alternative is.
Anyone have any advice on troubleshooting? Or any experience with this issue?
thanks
EDIT :
This is sample javasctipt that loads in the index.phtml view
$(function()
{
$("form#News").submit(function()
{
$.ajax(
{
type: 'POST',
url: '/main/manage/validateajax',
data: $('form#News').serialize(),
success: 'success'
});
return false;
});
});
The body of the view is a div that showform.phtml loads into
showform creates a form called #News.
When I insert the js code into the body of showform, it works. When I append this to the headScript, it does not work.
Maybe it's a solution for you.
Requirement: scripts of your modal view have to be already loaded (for example inside the application.js)
$("#loadModalBtn").click(function(e){
e.preventDefault();
var url = $(this).attr("href");
$("#modalContainer").load(url, function(){ // that's the point
var urlForm = $("form#News").attr("action");
$("form#News").submit(function(){
$.ajax({
type: 'POST',
url: urlForm,
data: $('form#News').serialize(),
success: 'success'
});
return false;
});
}).dialog({
height: 140,
modal: true
});
});

jQuery Ajax Form Submit Fails

I am developing an MVC4 mobile app that uses several forms which are loaded into a section on the layout via ajax. I've got jQuery mobile set with Ajax turned off so I can manage the Ajax myself. Most of the forms work fine, the load and submit via ajax as they should. However, so far there is one form that refuses to fire the form submit and submit the form via ajax like the rest. First, the form is loaded when a user clicks to add a contact and this works fine:
// Handle the add contact button click
$('#btnAddNewContact').on('click', function (e) {
e.preventDefault();
// Make sure a location was selected first.
var locationID = $('#cboLocation').val();
if (locationID.length === 0) {
//$('#alertTitle').text('REQUIRED');
$('#alertMsg').html("<p>A Contact must be associated with a Location.</p><p>Please select or add a Location first.</p>");
$('#alertDialogDisplay').click();
} else {
SaveOpportunityFormState();
$.cookie('cmdLocationId', locationID, { path: '/' });
$.mobile.loading('show');
$.ajax({
url: '/Contact/Add',
type: 'GET',
cache: false,
success: function (response, status, XMLHttpRequest) {
$('section.ui-content-Override').html(response);
// Refresh the page to apply jQuery Mobile styles.
$('section.ui-content-Override').trigger('create');
// Force client side validation.
$.validator.unobtrusive.parse($('section.ui-content-Override'));
},
complete: function () {
$.cookie('cmdPreviousPage', '/Opportunity/Add', { path: '/' });
AddContactLoad();
ShowSearchHeader(false);
$.mobile.loading('hide');
},
error: function (xhr, status, error) {
// TODO - See if we need to handle errors here.
}
});
}
return false;
});
Notice that after successfully loading the form the AddContactLoad() function is fired. This works fine and here is that code:
function AddContactLoad() {
$('#contactVM_Phone').mask('(999) 999-9999? x99999');
$('#frmAddContact').on('submit', function (e) {
e.preventDefault();
if ($(this).valid()) {
$.mobile.loading('show');
$.ajax({
url: '/Contact/Add',
type: 'POST',
cache: false,
data: $(this).serialize(),
success: function (response, status, XMLHttpRequest) {
if (!response) { // Success
ReturnToAddOpportunity();
} else { // Invalid Form
$('section.ui-content-Override').html(response);
// Force jQuery Mobile to apply styles.
$('section.ui-content-Override').trigger('create');
// Force client side validation.
$.validator.unobtrusive.parse($('section.ui-content-Override'));
AddContactLoad();
$.mobile.loading('hide');
}
},
complete: function () {
},
error: function (xhr, status, error) {
// TODO - See if we need to handle errors here.
}
});
}
return false;
});
$('#btnCancel').on('click', function (e) {
e.preventDefault();
// See where add contact was called from.
var previousPage = $.cookie('cmdPreviousPage');
if (previousPage.indexOf("Detail") >= 0) {
ReturnToOpportunityDetails();
} else {
ReturnToAddOpportunity();
}
return false;
});
}
If I click the cancel button, that code is fired so I know this is working too. Here is my form code:
#using (Html.BeginForm("Add", "Contact", FormMethod.Post, new { #id = "frmAddContact" }))
{
#Html.ValidationSummary(true)
#Html.AntiForgeryToken()
-- Form Fields Here --
<div class="savecancel" >
<input type="submit" value="Save" data-mini="true", data-theme="b", data-inline="true" />
Cancel
</div>
}
As you can see the form is named frmAddContact and that is what the AddContactLoad() function is attaching the submit event to. To save my sole I cannot figure out why the form does not submit via the ajax post like every other form in the app. Am I missing some kind of initialization, I just don't know. If anyone can please help I'd really appreciate it!!
As it turns out, I had created a custom unobtrusive Ajax validator for a phone number then copied and pasted it to do the same with a zip code. Unfortunately in the process I forgot to rename a variable and thus an error was occurring in the validation script which caused the problem. In the mean time, if you're reading this, you might take a note of the code here and how to inject HTML into a page via Ajax and jQuery mobile. I've never found this in a book or on the web and it contains some very useful methodology and syntax. On the form submit the reason I'm checking for the empty response is I just return null from the controller to validate the form was valid and the save worked in which case I send them to a different HTML injection i.e. that page they originally came from. If null is not returned I inject that page with the HTML containing the original form and error markup so the user can make corrections then resubmit. I'm also calling a form load method that attaches handlers to the HTML once it's injected into the main page. Hope this helps somebody!

jQueryUI Modal open event & MVC.NET causing error ".dialog is not a function"

I hope someone can help as I'm at my wits end with this. What I'm trying to do is this.
"Draggable" Item is Dropped into a "Droppable" area (this works)
This posts the id of the item to my controller which returns the type of item it is (this works)
I pass the returned item name to a function which opens a modal and renders a partial view in the modal depending on the particular item.
The last bit is where the issue is. All the steps above work fine, the modal is popped and the partial view is rendered to the modal. But the button to close the dialog throws the error ".dialog is not a function" and after closing the modal using the 'x' in the corner subsequent attempts to open the modal will not work throwing a similar error.
Here's the example I'm working with to try get this working.
$(function () {
$('.draggable').draggable({ containment: '#imageboundry', revert: 'valid' });
$('#droppable').droppable({
drop: function (event, ui) {
$.ajax({
type: "POST",
url: '/Home/AddToCart/' + $(ui.draggable).attr("id"),
success: function (data) {
getItemType(data);
}
});
}
});
});
function getItemType(itemName) {
$('#dialogs').dialog({
open: function () {
$(this).load("AdditionalContent", { itemName: itemName }, function () {
alert("This happened");
});
},
modal: true,
resizable: false,
title: itemName,
width: 400,
autoOpen: false,
buttons: {
"Confirm": function () {
$(this).dialog('close');
}
}
});
}
This is my controller which returns the partial view to the modal
public PartialViewResult AdditionalContent(string itemName)
{
return PartialView("_" + itemName + "Attributes");
}
The close button works once I take out the open: function () { ... } bit and I can reopen the modal again and again but once I put this back in the error gets thrown. This is obviously the cause but cannot for the life of me figure out why.
Thanks in advance for your help and sorry for the very long post.
UPDATE:
I've attempted initializing the modal in document.ready and call it from my "drop" function in the first main function. From doing this I've narrowed it down to this line of code which loads the partial view from my controller. Without this line the functionality works. Any ideas on what is wrong with this.
$(this).load("AdditionalContent", { itemName: itemName }
I figured it out. Included in the partial views was a second call to the jQuery library which was added automatically when the view was created. Plus it was version 1.4.4 while I was using 1.5.1 straight from Google in the _Layout page. The second jQuery library was obviously breaking the functionality as there was a conflict between the two versions. It wasn't until I watched the FireBug console that I noticed the second loading of the 1.4.4 library.
Thanks to all for your help, feel like a bit of an idiot but lesson learned..... for now
could try this but i am not sure
$('#dialogs').dialog({
var self = this;
open: function () {
$(self).load("AdditionalContent", { itemName: itemName }, function () {
alert("This happened");
});
},

Categories

Resources