jQuery Mobile - Dynamically creating form elements - javascript

I'm creating a web-database driven offline web-app targeted at iOS devices. I'm trying to use jQuery Mobile, but I have a problem in creating the various forms.
The form options are taken from a database query, so they are inserted into the page after it has loaded, so the "jQuery-Mobilification" doesn't happen. Taking a quick look through the source, there doesn't seem to be any obvious way to call into this at this stage (of course it's an alpha release, and I think this would be a reasonably common request, so I'm hopeful it will come). Is there some kind of workaround I can put in to do this? I'm particularly interested in radio buttons, check boxes and select lists.

UPDATE
Beta2 has a create event. I will update my faq when the beta2 gets released. See http://jquerymobile.com/blog/2011/07/22/jquery-mobile-team-update-week-of-july-18th/
Updated faq: http://jquerymobiledictionary.pl/faq.html
As CaffeineFueled proposed - .page() is the way to make JQM work with any part of HTML
.page() can be called only once for an element. Call it on a wrapping element you add to the page. It should handle everything.

The current selected answer is slightly out of date. Use 'refresh', not 'page', for styling dynamically added content (lists or forms).
If you add items to a listview, you'll
need to call the refresh() method on
it to update the styles and create any
nested lists that are added. For
example, $('ul').listview('refresh');
via the jQuery Mobile docs, 1.0.4a

This is messing around in undocumented internals, but the following is working for me:
$("#some-div").load("/html/fragment/",
function() {
$(this).find("input").customTextInput();
});
There are equivalent methods for buttons, checkboxes etc.
Have a look at the _enchanceControls [sic] method in http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.js.
Update for 1.0Alpha2: As can be expected when playing around with the internals of a library, this no longer works in the latest version. Changing customTextInput() to textinput() fixes it a bit, but the theme isn't fully applied for some reason. We were warned...

After your AJAX call finishes and you insert the form elements try calling:
$("#the-page-id").page();
I believe the jquery-mobile team will be adding a .refresh() method on the various UI elements to solve this issue in the future.

Yeah the issue is as you described. The 'mobilization' is fired when the document is ready. But since your offline DB queries are asynchronous it ends after the document.ready is fired. So the DOM is updated later in the process and doesn't have the extra CSS added to all the divs and list items.
I think you would have to change the source of the mobile js to not run on document ready but run when you tell it to run. Then you would have to call that function in your database callback.
Looks like that is the only option at the moment.
Traditionally I used jqtouch and now sencha. I haven't played much with jQuery mobile.
ALTERNATIVELY - you could write out your HTML after querying it out of the database with the necessary CSS styles on it. If you use Firebug plugin for Firefox you can see what styles / classes are getting applied when the mobilization runs. You could just write out your HTML using those conventions. Not ideal, but would work.

naugtur is right, you have to call .page() on any element that you add to the dom, then it works out nicely:
var el = $('<input type="text"/>')
el.page();
$('#something').append(el);

This worked for me (jquerymobile1.7.0):
$('#formular').append('<div data-role="fieldcontain" class="ui-hide-label">' +
'<label for="name" class="ui-hidden-accessible">Name:</label>' +
'<input type="text" name="name" size="25" id="name" placeholder="Name"/>' +
'</div>');
$('#name').textinput();
There are currently so called plugin functions for all kind of form elements (e.g. slider, textinput etc.) to create them.

Here's a link to the docs for this feature that Tom talked about. Not sure exactly when they were added, but I'm using it and it works for me!
http://jquerymobile.com/test/docs/forms/plugin-eventsmethods.html

Related

jQuery document ready with Knockout.js

I just got thrown into the Umbraco ASP.NET CMS for my latest project, I'm not sure if this is how it across the board but for my setup Knockout.js is doing all the templating.
I'm not too keen on knockout.js but so far it's been pretty straight forward except for when I start adding in some jQuery stuff, the problem I'm having is jQuery is firing before knockout has finished populating the page with all the elements.
The only solution that's worked for me thus far is all my jQuery stuff is wrapped in the setTimeout() function, which obviously is no good.
What's the most efficient way to make jQuery and Knockout work together so jQuery doesn't before knockout is done?
I recently had the same issue with the jSignature plugin and my Knockout view. I needed the KO view to have fully rendered before I invoked jSignature, otherwise it didn't size itself correctly.
I fixed it with a template binding and an afterRender callback function to invoke the jQuery work.
Here's the KO docs:
http://knockoutjs.com/documentation/template-binding.html
Here's a quick jsfiddle showing how you can use it:
http://jsfiddle.net/PCbFZ/
The trick is that you can use the afterRender callback of the template binding without actually using a template itself. Instead, you wrap all your existing HTML in a div that will invoke the afterRender callback:
<div data-bind="template: {afterRender: initApp}">
<!-- your existing HTML here -->
</div>
initApp is the function that does the jQuery work.
I think that should generally do what you need, though if your HTML is particularly complex, or you have many views you need to render inside the one page, you might need to do a bit more work. Let me know how you get on - maybe I can try to help a bit more if this doesn't quite fix your issue as easily as it did mine!
Update - following the comment from JACL below - here's an extended version of the fiddle showing this technique also working with ko-if. Each time you show/hide the 'widget' using the checkbox, a different random colour is applied to indicate the afterRender function doing its work.
http://jsfiddle.net/PCbFZ/15/
You might use:
$(window).load(function(){ /* code */ }); instead of $(document).ready();
Perhaps window.load instead of document.ready will do the trick

Issue with LightSwitch restyling custom control with delayed rendering

I was playing around with a LightSwitch custom control using the simple code:
myapp.Facility_Details.ScreenContent_render = function (element, contentItem) {
$(element).append("<ul><li><label><input type='checkbox'/><span>Test</span></li></ul>");
}
And I notice LightSwitch makes a valiant effort to rewrite my HTML after I render it, adding it's own control styling classes to the HTML and doing a bit of re-organizing. I figured I could live with this & just get used to what it did, but then I hit a worse issue when I added some AJAX to the mix. When I do my actual rendering in the done method of a Promise the post-processing doesn't happen.
EG:
myapp.Facility_Details.ScreenContent_render = function (element, contentItem) {
contentItem.data.getCommodityGroups().done(function (data) {
$(element).append("<ul><li><label><input type='checkbox'/><span>Test</span></li></ul>");
});
}
Renders totally differently (Doesn't edit the HTML). I could live with this too, but then if I browse away from this page & back to it then it swaps over to the first display... I tried returning the Promise from render thinking maybe that'd let it wait for me to be done, but no dice.
Does anyone know how can I either:
a) Prevent this reprocessing so I get the HTML I write every time.
b) Trigger this reprocessing explicitly so I can make sure it happens after I render inside a Promise.
It is jQuery doing the work so wrap into jQuery object before appending it perhaps?
Look at the samples down the page here MSDN article.
This restyling is coming from jQuery Mobile. Turns out the solution is to trigger a create event after editing the HTML (EG: $(element).trigger('create');) to tell jQuery Mobile there's new HTML to style.
Another approach is to add data-role='none' so jQuery Mobile leaves your HTML alone. I'll probably mostly use the latter, but it's good to know both exist.
Actually found the answer over at another StackOverflow question - the trick was knowing it was jQuery Mobile that mattered which is a lot easier to find info for than LightSwitch itself.

TinyMCE - how do you use onClick instead of <a href=""> for links?

Is there a way to change the defalt behaviour of TimyMCE, so that when you insert a link, it renders something like this:
<span onclick="window.open('http://google.com', '_blank', 'location=yes');"></span>
instead of
Ideally, I would like this to be done by the Link button, but it could be done onSubmit.
ADDED:
The reason for doing this (as I know it seems like bad practice) is to be able to port to PhoneGap (using the InAppBrowser plugin), as is not intended for browser use.
Overlooking that this really isn't a good practice, I will assume you have a valid use case for wanting to do such black magic.
But before, a few things to consider:
I would advise you to keep links as links while working in TinyMCE. That way, your users will be able to insert and edit them as usual. Changing them to span elements inside the editor will practically eliminate the ability to edit them without editing the full source. You should probably convert them to span elements outside the editor.
If you're the stubborn type and don't care about #1 or your users, you should note that the default TinyMCE 4 configuration doesn't allow onclick attributes, so you'll need to update extended_valid_elements, otherwise they will be removed during the cleanup process.
There is probably a better way to do what you're trying to do. As #Vic suggested, an event listener would probably be a better option.
Nevertheless, I will humor you. Below is an overview of the process with a working example.
Overview
If you are developing with TinyMCE 3.x, you'll want to tap into the onSaveContent event. If you are using 4.x, use the saveContent event. In both cases, the concept is the same.
This event gets fired whenever the content of the editor is "saved". This happens automatically if TinyMCE is submitted as part of a form, but you can also use tinymce.triggerSave() to force it on all editors at once.
So, simply setup your callback function to replace all links with the evil span alternative. You can use pure JS or TinyMCE's built-in DOM utilities (probably only a good idea if you're already familiar with them), but for clarity (and sanity) it's much easier with jQuery.
Working Example
TinyMCE Fiddle: http://fiddle.tinymce.com/mAdaab/1
This example uses TinyMCE 4
Open your browser's console to see the output
After TinyMCE loads, press the Save button
The resulting HTML will appear in your console
Do with it what you wish, but remember that there probably is a better way.
What you are proposing is a really bad practice (as in not using anchor tags for links) wouldnt it be easier to actually give your link an id or class and attach event listener with javascript and on click prevent default behavour grab the href attribute and use your window.open?

JqueryMobile issue when working with Knockoutjs

I found jquery mobile is not rendering correctly when the element is generated by knockoutjs (or probably not rendering correctly when element is generated dynamically). See the demo at http://jsfiddle.net/wRRZk/1/
updates:
One solution is to load jquery-mobile js file after KO binding finished as shown in http://jsfiddle.net/wRRZk/3/, however this doesn't solve the problem that jquerymobile render fail when changing KO model dynamically, as shown in http://jsfiddle.net/wRRZk/4/
I think you'll need to tell jQueryMobile to create those elements into the jQM enhanced version using the API. Check here :: http://jquerymobile.com/demos/1.1.1/docs/pages/page-scripting.html and look halfway down for "Enhancing new markup" and the section just below.
As for the create/refresh ... might need to be somewhat judicious in know when and where you're adding new stuff, and whether a create or refresh is needed.
I've done a new version of the jsFiddle here :: http://jsfiddle.net/wRRZk/5/.
I'm also removing from the model afterwards, which does seem to remove the links too, BUT, I think that may also be because the jQM enhancement is keeping the same anchor, thus the reference knockout as is still valid.
Not too sure how well that will work for the other enhancements done by jQM.

Is $.empty() enough for big ajaxy apps?

Been working on an App and since it's getting a bit too big I've thinking of ways to improve memory management since the app runs mostly on Javascipt. So every time a navigation item is clicked I would call the jquery empty then show the html via ajax. ex:
//$.ajaxSetup(); called before this
//$this is the attached element
$.ajax({success:function(data){
$this.empty().html(data.output).fadeIn(400);
//more javascript stuff like loading tinymce or jquery ui
}});
is this enough to prevent memory leaks? I'm not entirely sure what empty does but I'm assuming it removes all DOM elements within that div along with any other objects and events? btw. You can find the app here http://webproposalgenerator.com/ and http://webproposalgenerator.com/demo.
any tips on improving the performance/security or any feedback at all would be greatly appreciated.
$.fn.empty should be enough, it deletes all data and events associated to the elements and then deletes the elements. It also calls .widget("destroy") on all jquery-ui widget.js based widgets that are defined on those elements.
It is also important to note that jquery's $.fn.html method calls $.fn.empty() on the given element before appending html, therefore, if you are using $.fn.html, you don't have to call $.fn.empty
actually my guess was that .html implies .empty anyway, also I'm not sure that's true. for the perforamnce part: according to jqfundamentals excelent book it is a recommanded best practice to add content while the element is in .detach() from the DOM. tried to lock at the code for advice but didn't find it. nice site btw

Categories