Adding jQueryUI selectable items using AJAX - jquery-ui

I'm using some AJAX (ASP.NET Web Forms) to add new selectable elements on my site but the newly created ones aren't selectable. I guess this has to do with some events. Maybe it can be solved by using .on on those functions but I don't know how to do it. Anyone know how to fix that?
Here's my code:
$(".selectable").selectable({
filter: '.ui-widget-content',
stop: function () {
var result = $("#select-result").empty();
$(".ui-selected", this).each(function () {
var index = $(this).attr('id');
index = index.substring(12, index.length);
result.append(" #" + index);
});
}
});

when you load your page, jquery assign respective functions to each html tags. when you create some new div/html tags you should re-initialize the function because jquery doesn't know about your newly created html tags,
for the respective query
try re initializing the jquery function after adding new selectable element
hope this help..

Related

Grab all fieldset elements inside div

In my ASP MVC 3 view I have a number of fieldset elements that are hidden when the page loads. Based upon a user selection of a group of radio buttons, I need to make the corresponding fieldset visible.
I'd like to do this in jquery by making an array of the fieldset elements, then cycle through them, adjusting their visibility property if they match the selected radio button or not. Is this possible?
Since there is so much code in the fieldsets I attached the screen shot below to save space/make it more readable. The fieldsets I am trying to alter are inside of the RightDiv. If you need any more detail, please let me know. Thx
You can try this:
$(function(){
$('[name="TransactionType"]').change(function(){
var id = '#' + this.className; //Get the id from the clicked radio classname
$('#RightDiv').find('fieldset').hide();// hide all fieldsets;
$('#RightDiv').find(id).show(); // show the selected one.
});
});
Just note that in your html helper you are providing the the first overload as same name for all. All is well except i believe it will create duplicate ids for each of these. You may want to override it in the HTMLattributes.
#Html.RadioButton("TransactionType", false, new{#class="Enroll", id="Radio1"})
#Html.RadioButton("TransactionType", false, new{#class="New", id="Radio2"})
Sorry, posted a bit too soon on this. Tried the following below and it worked just fine.
$(document).ready(function () {
$('input[name=TransactionType]').change(function () {
var radioValue = $(this);
var elements = [];
$('#RightDiv').children().each(function () {
elements.push($(this));
});
});
});

Chosen not working in jquery dialog on reloading mvc partial

I am loading two MVC Partial Views in jQuery UI dialog using following code for editing and adding a record:
$.get(url, function(data)
{
dialogDiv.html(data);
var $form = $(formid);
$form.unbind();
$form.data("validator", null);
$.validator.unobtrusive.parse(document);
var dat = $form.data("unobtrusiveValidation");
var opts = dat ? dat.options || '' : '';
$form.validate(opts);
//THIS FUNCTION ADDS PLUGINS ETC.
runEditCreateStartScripts();
dialogDiv.dialog('open');
});
Following is the function that wires-up chosen functionality.
function runEditCreateStartScripts(){
$("select.chzn-select").chosen(
{
no_results_text: "no match",
allow_single_deselect: true
});
}
Everything is perfect on first call. After opening one dialog say edit a few times everything is broken. There is only hyperlink available in place of chosen stuff. This also happens if I open one dialog say add and then second dialog. The bindings and other functionality from first one (add) is gone.
Any insights on why this might be happening?
The problem that caused my issue was that the modals I was loading via AJAX had inputs with the SAME ID as an input field that was already on the page (using Django that has generic ID generators for model fields). This caused collision between the two inputs when re-triggering .chosen() on the selector. When I made the ID fields unique, all worked as expected.
Hope this would have helped.

JQM - Inject dynamic content at load time only

I'm trying to dynamically populate a select tag at load time (latest jQM version) using a custom template filling function.
If the fn is called in the "pagebeforechange" event, the select tag is properly initialized. Since this event is called on every page transition, I thought of moving the fn to the 'pageinit' event. This does not work, presumably because the DOM is not yet fully available. How can I coerce jQM to inject content in a page only once? Currently, I am using a kludge. There surely must be a smarter way. Thanks for any suggestions.
$(document).bind('pageinit', function () {
InitSelTagTest("#selActTag", "tplTag"); // Does not work.
});
$(document).bind("pagebeforechange", function (e, data) {
if ($("#selActTag").children().size() === 0) {
InitSelTagTest("#selActTag", "tplTag"); // Kludge, but it works
}
});
function InitSelTagTest(el,tpl) { // Append all tags to element el
var lstAllTags = JSON.parse($("#hidTag").val()); // Create tag array
// Retrieve html content from template.
var cbeg = "//<![" + "CDATA[", cend = "//]" + "]>";
var rslt = tmpl(tpl, { ddd: lstAllTags }).replace(cbeg, ").replace(cend,");
$(el).html(rslt).trigger("create"); // Add to DOM.
}
EDIT
In response to Shenaniganz' comment, it seems that the "pagebeforecreate" event could do the trick ie.
$("#pgAct").live("pagebeforecreate", function () {
// Populate tag select. Works. Traversed only once.
InitSelTag("#selActTag", "tplTag");
});
I'm not sure I fully understand your question but I'll throw a few things out there and you let me know if I can extend further.
To make something trigger only once on page load you can try to implement a regular JQuery $(document).ready(function(){}) aka $(function(){}) for the exact reason why JQuery Mobile users are told not to use it. It triggers only once on DOM load. Further pages don't trigger it because they're being switched via Ajax.
Other than that, on regular dynamic content loading you take a look at the following example I put together for someone else earlier:
http://jsbin.com/ozejif/1/edit

jQuery UI in Backbone View adds elements, but doesn't respond to events

I'm building an app in which I'm using Django on the backend and jQuery UI/Backbone to build the front. I'm pulling a Django-generated form into a page with jQuery.get() inside of a Backbone View. That part works fine, but now I want to add some jQuery UI stuff to the form (e.g. a datepicker, some buttons that open dialogs, etc). So, here's the relevant code:
var InstructionForm = Backbone.View.extend({
render: function() {
var that = this;
$.get(
'/tlstats/instruction/new/',
function(data) {
var elements = $(data);
$('#id_date', elements).datepicker();
that.$el.html(elements.html());
}
};
return this;
}
});
The path /tlstats/instruction/new/ returns an HTML fragment with the form Django has generated. What's happening is that input#id_date is getting the hasDatePicker class added and the datepicker div is appended to my <body> element (both as expected), but when I click on input#id_date, nothing happens. No datepicker widget appears, no errors in the console. Why might this be happening?
Also, somewhat off-topic, but in trying to figure this problem out on my own, I've come across several code examples where people are doing stuff like:
$(function() {
$('#dialog').dialog(...);
...
});
Then later:
var MyView = Backbone.View.extend({
initialize(): function() {
this.el = $('#dialog');
}
});
Isn't this defeating the purpose of Backbone, having all that jQuery UI code completely outside any Backbone structure? Or do I misunderstand the role of Backbone?
Thanks.
I think your problem is right here:
$('#id_date', elements).datepicker();
that.$el.html(elements.html());
First you bind the datepicker with .datepicker() and then you throw it all away by converting your elements to an HTML string:
that.$el.html(elements.html());
and you put that string into $el. When you say e.html(), you're taking a wrapped DOM object with event bindings and everything else and turning into a simple piece of HTML in a string, that process throws away everything (such as event bindings) that isn't simple HTML.
Either give .html() the jQuery object itself:
$('#id_date', elements).datepicker();
that.$el.html(elements);
or bind the datepicker after adding the HTML:
that.$el.html(elements);
that.$('#id_date').datepicker();

Creating a jQuery UI sortable in an iframe

On a page I have an iframe. In this iframe is a collection of items that I need to be sortable. All of the Javascript is being run on the parent page. I can access the list in the iframe document and create the sortable by using context:
var ifrDoc = $( '#iframe' ).contents();
$( '.sortable', ifrDoc ).sortable( { cursor: 'move' } );
However, when trying to actually sort the items, I'm getting some aberrant behavior. As soon as an item is clicked on, the target of the script changes to the outer document. If you move the mouse off of the iframe, you can move the item around and drop it back by clicking, but you can not interact with it within the iframe.
Example: http://robertadamray.com/sortable-test.html
So, is there a way to achieve what I want to do - preferably without having to go hacking around in jQuery UI code?
Dynamically add jQuery and jQuery UI to the iframe (demo):
$('iframe')
.load(function() {
var win = this.contentWindow,
doc = win.document,
body = doc.body,
jQueryLoaded = false,
jQuery;
function loadJQueryUI() {
body.removeChild(jQuery);
jQuery = null;
win.jQuery.ajax({
url: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js',
dataType: 'script',
cache: true,
success: function () {
win.jQuery('.sortable').sortable({ cursor: 'move' });
}
});
}
jQuery = doc.createElement('script');
// based on https://gist.github.com/getify/603980
jQuery.onload = jQuery.onreadystatechange = function () {
if ((jQuery.readyState && jQuery.readyState !== 'complete' && jQuery.readyState !== 'loaded') || jQueryLoaded) {
return false;
}
jQuery.onload = jQuery.onreadystatechange = null;
jQueryLoaded = true;
loadJQueryUI();
};
jQuery.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
body.appendChild(jQuery);
})
.prop('src', 'iframe-test.html');
​
Update: Andrew Ingram is correct that jQuery UI holds and uses references to window and document for the page to which jQuery UI was loaded. By loading jQuery / jQuery UI into the iframe, it has the correct references (for the iframe, rather than the outer document) and works as expected.
Update 2: The original code snippet had a subtle issue: the execution order of dynamic script tags isn't guaranteed. I've updated it so that jQuery UI is loaded after jQuery is ready.
I also incorporated getify's code to load LABjs dynamically, so that no polling is necessary.
Having played with their javascript a bit, Campaign Monitor solves this by basically having a custom version of jQuery UI. They've modified ui.mouse and ui.sortable to replace references to document and window with code that gets the document and window for the element in question. document becomes this.element[0].ownerDocument
and they have a custom jQuery function called window() which lets them replace window with this.element.window() or similar.
I don't know why your code isn't working. Looks like it should be.
That said, here are two alternative ways to implement this feature:
If you can modify the iframe
Move your JavaScript from the parent document into iframe-test.html. This may be the cleanest way because it couples the JavaScript with the elements its actually executing on.
http://dl.dropbox.com/u/3287783/snippets/rarayiframe/sortable-test.html
If you only control the parent document
Use the jQuery .load() method to fetch the content instead of an HTML iframe.
http://dl.dropbox.com/u/3287783/snippets/rarayiframe2/sortable-test.html
Instead of loading jQuery and jQueryUI inside the iFrame and evaluating jQueryUI interactions both in parent and child - you can simply bubble the mouse events to the parent's document:
var ifrDoc = $( '#iframe' ).contents();
$('.sortable', ifrDoc).on('mousemove mouseup', function (event) {
$(parent.document).trigger(event);
});
This way you can evaluate all your Javascript on the parent's document context.

Resources