how to create a jquery mobile select menu at pagebeforeshow? - javascript

I'm using dataTables with Jquery Mobile. My dataTable is initiated on pageBeforeShow. Inside my init callback function I construct a JQM select menu. This menu does not get properly enhanced = the button is there, but the custom-select is not created.
That's my problem!
Here's the shortened code:
$('div:jqmData(role="page")').live('pagebeforeshow', function(e, data) {
/** init datatables **/
$('.tbl_orders').dataTable( {
/* callback */
"fnInitComplete": function(oSettings, json) {
var thead = $(oSettings.nTHead),
bodyRows = $(oSettings.nTBody).find("tr, TR"),
hdrCols = thead.find( /* all header columns */ );
/* create select */
tableSelectMenu = $('<select name="toggleCols" id="toggleCols" multiple="multiple" data-icon="setup" data-iconpos="notext"></select>')
/* loop through header cols add options */
hdrCols.each(function(i){
var toggle = $('<option value="'+id+'">'+th.text()+'</option>');
tableSelectMenu.append(toggle);
}); // end hdrCols loop
$('.stickSelectHere').append(tableSelectMenu)
}
});
If I do it like this, the select button is there but does not do anything, because the custom-select-menu is missing.
I tried to create the select earlier on pagebeforecreate, because that's where I'm checking for touch devices and assigning data-native-menu="true/false". But putting the select there, also doesn't do any good, maybe because I just create it and don't drop it in the DOM until my tableInit... mh.
Question:
Can someone tell me how to create a select with custom-menu at pagebeforeshow?
Thanks for help!

You likely just need to add the following after your append, i.e.
$('.stickSelectHere').append(tableSelectMenu)
$('#toggleCols').selectmenu('refresh');

Related

Unable to highlight datatable row

In the example below highlighting works quite well with individual rows.
In my code I can see that selection of an individual row works, however, the actual highlighting does not work.
I am using Twitter Bootstrap 3 + Datatables.
http://datatables.net/release-datatables/examples/api/select_single_row.html
Any help would be appreciated. I have followed the example as is and I think perhaps I have not configured the table properly in its init or Bootstrap does not quite like highlighting.
var oTable;
$( document ).ready(function() {
/* Add a click handler to the rows - this could be used as a callback */
$("#pTable tbody tr").click( function( e ) {
if ( $(this).hasClass('row_selected') ) {
$(this).removeClass('row_selected');
}
else {
oTable.$('tr.row_selected').removeClass('row_selected');
$(this).addClass('row_selected');
}
});
/* Add a click handler for the delete row */
$('#deletePButton').click( function() {
var anSelected = fnGetSelected( oTable );
if ( anSelected.length !== 0 ) {
oTable.fnDeleteRow( anSelected[0] );
}
});
/* Init the table */
oTable = $('#pTable').dataTable( );
/* Get the rows which are currently selected */
function fnGetSelected( oTableLocal )
{
return oTableLocal.$('tr.row_selected');
}
});
So the deleteButton which is being referenced in the code works if I select a row and delete a row.
Just the highlighting doesnt work!
Is your table id "#pTable"?
Did you try adding a debbug stop on that method, to be sure that the selector is working?
On bootstrap to hightlight a row you must use one of this classes
Class Description
.active Applies the hover color to a particular row or cell
.success Indicates a successful or positive action
.warning Indicates a warning that might need attention
.danger Indicates a dangerous or potentially negative action
Bootstrap 3 Tables

Select2 Dropdown Dynamically Add, Remove and Refresh Items from

This drives me crazy! Why cant Select2 implement clear methods or examples on their page how to do simple CRUD manipulation on Select2 :)
i have a select2 which gets data from a ajax call.
<input id="valueg" type="hidden" style="width: 300px;" data-placeholder="Select a Conference" />
$("#valueg").select2({
data: conferences,
allowClear: true,
initSelection: function (element, callback) {
var data = { id: element.val(), text: element.val() };
callback(data);
}
}).on("change", function (e) {
// show data in separate div when item is selected
});
Can some one provide a clear method how to delete and add an item from the Select2.
For example:
I add an item via ajax call to db, and just want to append an option to Select2 and set it as selected.
I remove an item via ajax to db, and want to remove an option from Select2 and have no option selected.
From your example I can see that you attached Select2 plugin to hidden element. In addition you use Ajax call to populate results, so in this case if you need to add a new option to the list you simple call:
$('#valueg').select2('val', 'YOUR_VALUE');
In case of using select element as a container the only way that I found is to reinitialize plugin with new options... Something like this:
var el = $('select[name="type"]', '#details-form');
var temp = el.select2('val'); // save current value
temp.push(NEW_VALUE); // append new one
var newOptions = '<option value="1">1</option><option value="2">2</option>';
el.select2('destroy').html(newOptions ).select2().select2('val', temp);
I did it this way:
var $select2 = $('#valueg').select2(); // getting the select2
var item = 'xyz'; // item to be added
$select2.val(function(i, val) { // val can take function as parameter
val = val || []; // if value is null init val as an array
val.push(item); // add the new item
return val;
}).trigger("change"); //refresh
Hope that helps
I had the same issue. This is how i solved it
This has nothing to do with select2, manipulating the itself seems to work for me
$("#lstService").empty();
for(var i=0;i<data.length;i++){
$("#lstService").append('<option value="'+data[i].service_id+'">'+data[i].service_name+'</option>');
}
In my case, the key thing to add after manipulating the underlying select is:
$selectlist.trigger("change"); //$selectlist is the underlying select element.
Select2 works around the change event on a select, so calling "change" updates the option displayed in the select 2.
It is too late... but this is my solution for people that still have this problem:
html = "";
jQuery("#select_2 option").each(function()
{
html += '<option value="'+jQuery(this).attr("value")+'">'+jQuery(this).text()+'</option>';
});
html += '<option value="NEWVALUE">NEW OPTION</option>';
jQuery("#select_2").html(html);

Add & Remove element IF class has x style...not working properly

I'm using a jquery quick search plugin (https://github.com/riklomas/quicksearch) which filters a list based upon the data entered into an input field.
If there's no results returned, I want to display a message saying so.
The quick search plugin adds display: none to all list elements that aren't to be shown.
Therefore, I tried this:
// load jquery.quicksearch
$('#search').parent().css('display','block').end().quicksearch('#ul'+id+' li');
// show / hide message
$("input#search").keypress(function() {
li = $('.category li');
if (li.css('display') == 'none') {
$('body').append('<div id="noContent">no content</div>');
} else {
$('#noContent').remove();
}
});
The result is a very twitchy / buggy solution. Some times it doesn't append the message even if all li items have display: none. It also doesn't even remove the no content message even when there ARE list items visible.
Any ideas?
Read the docs: you don't need to do what you're doing.
Simply use the noResults option.
Their example:
$('input#search').quicksearch('table tbody tr', {
'delay': 100,
'selector': 'th',
'stripeRows': ['odd', 'even'],
'loader': 'span.loading',
'noResults': 'tr#noresults',
.......
looks like you would want 'noResults': '#noContent'

Jquery - Initialize Select Box after first use

Page is loaded with a hidden select box in it.
I click on a button
I append elements to this select box, I move it and I make it visible
I apply plugin Chosen on it
This is done by this function
function moveHiddenSelect(idOffline, type, idMedia, mediaName){
var $selToReplace = $("#"+type+"_"+idOffline);
var $selOriginal = $("#originalSelect");
$selToReplace.replaceWith($selOriginal);
$.getScript('/lib/chosen/chosen.jquery.min.js', function(){
$selOriginal.chosen(); //load plugin script and apply it on the select box
});
$selOriginal.css("width", "220px");
$selOriginal.css("visibility", "visible");
}
No problem when I click the button one time, but when I click again on the button (step 2) nothing is happend..
The chosen() should be called once, just for creation.
After updating the values of each dropdown, you could use: $(DropdoenElement).trigger("liszt:updated");
function moveHiddenSelect(idOffline, type, idMedia, mediaName){
var $selToReplace = $("#"+type+"_"+idOffline);
var $selOriginal = $("#originalSelect");
$selToReplace.replaceWith($selOriginal);
selOriginal.chosen(); // Init the plugin
$.getScript('/lib/chosen/chosen.jquery.min.js', function(){
//load plugin script and apply it on the select box
selOriginal.trigger("liszt:updated")
});
$selOriginal.css("width", "220px");
$selOriginal.css("visibility", "visible");
}
Hope it helps!

jQuery Font Selector: show&hide with focus

I'm trying to implement a jQuery Font Selector in my project but I have some troubles to achieve it. I'm using the source code I found here jQuery Font Selector
You can see the demo here
Everything is working great, except the author of this code hasn't included a function that close the "scrolling menu" if we clicked anywhere else on the screen. You're forced to choose something inside that list for this list to close.
I'm going to paste the code here so it'll be easier to explain.
/**
* Font selector plugin
*/
jQuery.fn.fontSelector = function() {
var fonts = new Array(
'Arial,Arial,Helvetica,sans-serif',
'Arial Black,Arial Black,Gadget,sans-serif',
/* other fonts */);
return this.each(function(){
// Get input field
var sel = this;
// Add a ul to hold fonts
var ul = $('<ul class="fontselector"></ul>');
$('body').prepend(ul);
$(ul).hide();
jQuery.each(fonts, function(i, item) {
$(ul).append('<li>' + item.split(',')[0] + '</li>');
// Prevent real select from working
$(sel).focus(function(ev) {
ev.preventDefault();
// Show font list
$(ul).show();
// Position font list
$(ul).css({ top: $(sel).offset().top + $(sel).height() + 4,
left: $(sel).offset().left});
// Blur field
$(this).blur();
return false;
});
$(ul).find('a').click(function() {
var font = fonts[$(this).attr('class').split('_')[1]];
$(sel).val(font);
$(ul).hide();
return false;
});
});
});
}
From here I tried to modify the code, like adding $(ul).hide(); inside the blur function... Works BUT that i don't want the input to be manually editable. I don't want the user to be able to modify the content of the input except by selecting a font.
I hope you're not to confused with what I'm asking !
Thanks for your help
EDIT: Some changes after discussion:
http://jsfiddle.net/ahkEv/4/
Add the following inside jQuery.fn.fontSelector = function() {
$("body").click(function(){
$(".fontselector").hide();
});
Change $(sel).focus to
$(sel).click(function(ev) {
and add the following to $(ul).find('a').click(function(ev) {
ev.stopPropagation();

Categories

Resources