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

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");

Related

Inserting dynamic panel jquery mobile

In my app I would like to re-use the panel so I call this function when opening index.html:
var add_panel=function() {
//add button
$('[data-role="header"]').append('Menu');
//panel
$.get('panel.html').success(function(data) {
$('div[data-role="page"]').append(data);
$('#leftpanel').trigger('create');
$('#leftpanel').panel();
});
//open panel
$('body').on('click', '.ui-icon-bars', function() {
$("#leftpanel").panel("toggle");
});
}
This works great on the first page and when returning to this page from another page.
I had hoped to call the same function inside "pagecontainertransition" to add the panel to other pages as well, but this doesn't seem to work:
//handle page transitions
$('body').on('pagecontainertransition', function(event, ui) {
add_panel();
});
Can this be done?

Ember.js + JQuery-UI Tooltip - Tooltip does not reflect the model / controller changes

Context
I have a small Ember app, which, amongst other things, displays a number of connected users and, when hovering an element of the page, their names as a list.
All in all, it works quite well. The applications pulls data from a REST endpoint every two minutes, as the backend didn't allow for pushing data.
The contents of the tooltip are computed in the Controller, with a function that basically concatenate strings in various ways according to the context. Then it's bound to a data attribute of the <img> the tooltip is created on. When the View is ready and didInsertElement is fired, the tooltip is generated (if needs be) based on this data-bindattr value.
Question
When new data is pulled from the backend, everything is updated accordingly, except the tooltip content. (When browsing the page's DOM, the data-bindattr value is updated too.)
What could cause the tooltip to not refresh? Is it a case of JQuery-UI not calculating it again?
Some code
Refreshing code in the app's controller:
Monitor.ApplicationController = Ember.ArrayController.extend({
itemController: 'process',
sortProperties: ['name'],
sortAscending: true,
intervalId: undefined,
startRefreshing: function() {
var self = this;
if (self.get('intervalId')) {
return;
}
self.set( 'intervalId', setInterval(function() {
self.store.find('process');
}, 120000 ));
}
});
View: Process.hbs
<div {{bind-attr class=":inline inactive:inactive"}}>
<img {{bind-attr src=icon}} {{bind-attr data-caption=contentText}} class="caption" />
<div class="counter">{{nbUsers}}</div>
</div>
View: ProcessView
Monitor.ProcessView = Ember.View.extend({
// (...) Various stuff.
didInsertElement: function() {
this.updateTooltip();
},
updateTooltip: function() {
console.log('Inside updateTooltip!');
if (!this.$()) {return;}
if (this.get('controller').get('inactive')) {
this.$().tooltip({items: '.caption', disabled: true});
return;
}
this.$().tooltip({
items: '.caption',
tooltipClass: 'tooltip',
content: function() {
return $(this).data('caption');
},
position: {
my: 'left+15px center',
at: 'right center',
collision: 'flip'
},
show: false,
hide: false
});
}.observes('controller.inactive', 'controller.contentText')
});
Controller: ProcessController
Monitor.ProcessController = Ember.ObjectController.extend({
contentText: function() {
var tooltipContent = '';
this.get('containers').forEach(function(container) {
// Do a lot of things to tooltipContent involving:
// container.get('name')
// container.get('text')
// container.get('size')
// container.get('nbUsers')
// The data-bindattr value refreshes correctly so I cut this out for readability.
return tooltipContent;
}.property('name', 'containers.#each')
});
Edit 1:
Replaced 'containers.#each' by 'contentText' in the observer and added logging.
Here's what I think is happening:
Your tooltip library isn't observing the data-caption attribute. Meaning, when you update the attribute, you have to explicitly tell the library to update the tooltip as well. So although your attribute is updating just fine, the tooltip library isn't actually watching for those updates.
This can be remedied by calling updateTooltip, which you do, in didInsertElement. However, didInsertElement only fires once, when the element is first inserted. It's not called when the content changes.
Those two things combined are, I think, causing your problem. I think that all you need to do is have updateTooltip also observe the controller.contextText property. Then it should be called when the text updates.
So it turns out my codes declares and initialize a tooltip, but once it's done, you can't change the content the same way. Plus it adds unneeded computing anyway.
Thanks to #GJK's answer and that question, I found out what was happening. Turns out you need to set the content of the tooltip to refresh it, not recreate it.
Here is the working code for Ember integration:
Monitor.ProcessView = Ember.View.extend({
// Other stuff
didInsertElement: function() {
this.initTooltip();
},
initTooltip: function() {
if (!this.$()) {return;}
if (this.get('controller').get('inactive')) {
this.$().tooltip({items: '.caption', disabled: true});
return;
}
this.$().tooltip({
items: '.caption',
tooltipClass: 'tooltip',
content: function() {
return $(this).data('caption');
},
position: {
my: 'left+15px center',
at: 'right center',
collision: 'flip'
},
show: false,
hide: false
});
},
updateTooltip: function() {
if (!this.$()) {return;}
if (this.get('controller').get('inactive')) {
this.$().tooltip({items: '.caption', disabled: true});
return;
}
content = this.get('controller').get('contentText');
this.$().tooltip("option", "content", content);
}.observes('controller.contentText')
});
As an added bonus, you can avoid using the data attribute as a buffer now, although I'm not sure why.

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!

Jquery Mobile - Dynamic Pages Accumulating in the DOM

I'm working on a simple Jquery Mobile application that does a search, presents results, and then allows you to click on a result to go to a dynamic detail page. On the detail page there is a collapsible list which uses an ajax call to get its content.
It appears to be working fine on the surface, but when I inspect it with Firebug I notice that every time you go to a detail page and expand the collapsible list, the ajax fires multiple times.
So, for instance, I do a search, go to the detail page, expand the collapsible list, the ajax fires once. I go back to the results page, click on another result, go to the detail page, expand the collapsible list, and the ajax fires twice, etc. Each time I expand the collapsible list, the ajax fires one more time...so if I look at 10 results, the ajax fires 10 times.
It would appear that the dynamic pages are accumulating in the DOM, and each time I click on the collapsible list, it's firing on all the selectors that have built up in the DOM (at least that's my theory).
How do I make sure that my ajax only fires once rather than multiple times?
I'm using Jquery Mobile 1.0.1 with Jquery 1.6.4. I'm using php to get the data.
Here's my code for the search page:
$('form#searchCompanies').submit(function(event) {
getSearchResultsCompanies();
return false;
});
function getSearchResultsCompanies() {
$.ajax({
type: "POST",
url: baseURL + 'server/searchCompanies.php',
data: $("form#searchCompanies").serialize(),
dataType: 'json',
success: function(results){
$('#companyList li').remove();
for ( var i=0; i < results.length; i++) {
$('#companyList').append('<li>' + results[i].CompanyName + '</li>');
}
$('#companyList').listview('refresh');
}
});
return false;
}
$('.companyDetail').live('click', function(event) {
//save companyid so that we can reference it on detail page
var companyid = $(this).attr('data-uid');
localStorage.setItem('thisCompanyId', companyid);
});
Here's the code for the detail page:
$('#companyDetailPage').live('pageshow', function(event) {
var companyid = localStorage.getItem('thisCompanyId');
$.ajax({
type: "POST",
url: baseURL + 'server/getCompanyDetail.php?companyid=' + companyid,
data: {companyid: companyid},
dataType: 'json',
success: function(company) {
$.each(company, function(index, company) {
$('#companyName').html(company.CompanyName);
//etc...pulls in more data to populate the page
});
}
});
//this is the call that fires multiple times
$('#companyContacts').live('expand', function(event) {
$('#companyContactList li').remove();
$.ajax({
type: "POST",
url: baseURL + 'server/getCompanyContacts.php?companyid=' + companyid,
dataType: 'json',
success: function(results){
for ( var i=0; i < results.length; i++) {
$('#companyContactList').append('<li>' + results[i].LastName + 'etc...more data</li>');
}
$('#companyContactList').listview('refresh');
}
});
return false;
});
});
The html div that gets populated looks like this:
<div data-role="collapsible" data-collapsed="true" id="companyContacts" class="cmdCompanyContacts">
<h3>Contacts (<span id="totalContacts"></span>)</h3>
<ul id="companyContactList" data-role="listview"><li></li></ul>
</div>
I've searched high and low for a resolution, and tried reworking my code from various angles, but I'm not able to solve this problem. Any help would be deeply appreciated. Thanks.
I had this problem too. I tried the suggestion found here, but still had the multiple event triggering problem after trying this. Here is what else I had to do. I changed it from this:
$(‘#myPage’).bind(‘pageinit’, function (event) {
$(‘#myButton’).live(‘click’, function (event, ui) {
to this:
$(‘#myPage’).bind(‘pageinit’, function (event) {
$(‘#myButton’).click(function (event, ui) {
Rather than using jquery live i would like to suggest you to use javascript function call when you click for the page change.Write your ajax call in that function so that its been called only once.Hope this helps

Prevent default on a click within a JQuery tabs in Google Chrome

I would like to prevent the default behaviour of a click on a link. I tried the return false; also javascript:void(0); in the href attribute but it doesn’t seem to work. It works fine in Firefox, but not in Chrome and IE.
I have a single tab that loads via AJAX the content which is a simple link.
<script type="text/javascript">
$(function() {
$("#tabs").tabs({
ajaxOptions: {
error: function(xhr, status, index, anchor) {
$(anchor.hash).html("Couldn't load this tab. We'll try to fix this as soon as possible. If this wouldn't be a demo.");
},
success: function() {
alert('hello');
$('#lk').click(function(event) {
alert('Click Me');
event.preventDefault();
return false;
});
}
},
load: function(event, ui) {
$('a', ui.panel).click(function(event) {
$(ui.panel).load(this.href);
event.preventDefault();
return false;
});
}
});
});
</script>
<body>
<div id="tabs">
<ul>
<li>Link</li>
</ul>
</div>
</body>
The content of linkChild.htm is
Click Me
So basically when the tab content is loaded with success, a click event is attached to the link “lk”. When I click on the link, the alert is displayed but then link disappears. I check the HTML and the element is actually removed from the DOM.
$('#selector').click(function(event) {
event.preventDefault();
});
The event object is passed to your click handler by default - you have to have something there to receive it. Once you have the event, you can use jQuery's .preventDefault() method to cancel the link's behavior.
Edit:
Here's the fragment of your code, corrected:
$('a', ui.panel).click(function(event) {
$(ui.panel).load(this.href);
event.preventDefault();
return false;
});
Notice the addition of the word 'event' when creating the anon function (or you could use just e, or anything else - the name is unimportant, the fact there's a var there is.

Resources