Is there a way to rename column labels such as instead of RequestID, it is Request Id, etc and order the table columns in such that the first row is RequestID and Request Date and the rest like etc?
Please ignore the alternating color formatting.
$("#example").on("click", "a[target='tab']", function(){
var me = $(this);
var url = me.attr("href");
var tabName = me.data("tabName");
var tabIndex = parseInt(me.data("tabIndex"), 10);
$.get(url, function(data) {
var table = $( '<table style="font-weight:bold;font-size:10pt;border-color:#ddd;" cellpadding="4" width="100%" cellspacing="0" />' ),
tr = $( '<tr/>' ),
td = $( '<td/>' ),
th = $( '<th/>' );
//alert(JSON.stringify(data));
$.each( data[ 0 ], function(key,value) {
tr.clone().html( td.clone().html( key.bold() ) )
.append( td.clone().html( value ) )
.appendTo( table );
});
$(tabName).html(table);
// Activate the tab once the page has loaded:
$("#tabs").tabs("option", "active", tabIndex);
}, 'json');
// Prevent the browser from following the link:
return false;
});
});
</script>
Thanks very much in advance for your assistance.
I have not been able to find any usable information on the web.
Your best bet would be to separate everything into logical tables or definition lists. You could mangle the table to look like the bottom result, but you're doing that on the fly, and is going to be pretty bespoke (and brittle) code.
I'm not sure if you have control over the rendering of the table (but it seems you do since you're using json data), but that would be where I would start looking. Failing that, you could break up sections with tr elements containing empty td elements, and add a class to the td to make them appear to be empty spaces. That's gross though, and isn't even remotely semantic.
Related
We can use cell().data() to set cell data. But what if we need to just update orthogonal cell properties, but not main display data, which is rendered in the cell? I.e. we have this data for the cell and we just want to update current_value while keeping display unchanged in the DOM:
"digit": {
"display": "<select><option selected value=`1`>1</option><option value=`2`>2</option></select>",
"current_value": "1"
}
My use case is using <select> within a cell — when option changes I want to keep select in place and only change orthogonal data.
You can use row().data() API method to get/set the data for the selected row.
For example, to increment current_value when a row is clicked on:
var table = $('#example').DataTable();
$('#example tbody').on( 'click', 'tr', function () {
var data = table.row( this ).data();
data.digit.current_value++;
table
.row( this )
.data( data )
.draw(false);
} );
on jQuery's website there is a documentation says,
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
For those who have used this method know that it adds all the json attributes into the the variable called "iteams" and then it converts the "items" into html by adding the string into a new unordered list with a class called "my-new-list".
Now, say if I do not want to add a new unordered list with a class called "my-new-list", instead I want to convert the new variable into string and add into an existed HTML element, say with a class called "curtain," how do I go about the do that?
Here is my try:
var items = [];
var first = '<div class="panel"><div class="panel-gallery"><img src="',
second = '" Alt=""></div></div>';
$.each( data, function( url ) {
items.push( first + url + second );
html: items.join( "" ).appendTo( ".curtain" );
});
Apparently that will give me an error on the line:
html: items.join( "" ).appendTo( ".curtain" );
It gives you an error because it is not a valid syntax because you are putting it in a function, not a hash. If items.join returns html, just remove "html:" and do this:
$(items.join( "" )).appendTo( ".curtain" );
will do the trick.
To answer your question, in a most simple way, it CANNOT be done.
Why?
Here is the documentation: http://www.w3schools.com/jquery/html_html.asp
In short, the .html() method in jQuery must have a "selector."
This means, you must have a selector to allow the objects to be convert into.
You have three ways to achieve your goal.
1) If you do not care to expand your variable "items", you can simple take it out from the code and use:
$('.yourClass').append(XXX);
It looks like your failed. This is because mounting string to DOM tree loop out the javascript engine on its first process, you can use load method but you might still fail. So you must use method 2 or 3.
2) Make use '.yourClass' is empty, and then:
$('.yourClass').html(XXX);
Now this is convenient but, you might not have an empty '.yourClass' so...
3) Creative a new class, lets call it '.newClass':
$( "<div/>", {
"class": "newClass",
html: items.join( "" )
}).appendTo( "body" );
And now take all the children of '.newClass' and append them to '.yourClass':
$(".newClass").children().appendTo(".yourClass");
Finally, remove '.newClass'.
$(".newClass").remove();
Difficult? Yes. That's how it has to be. Sorry pal.
I'm using Freebase Search Suggest to bind a certain keyword to a getJson request. The problem is that I bind getJson functions and the corresponding .append/.prepend functions to to the input field that has the search suggest. Now if want to clear(.empty) my div that contains the result from the getJson functions i end up not being able to appennd anything.
So every time I do a search the result div stays empty. If I not try to run the empty function and do a second search, the new information gets appended on top of the previous information.
My site www.karsten-tietje.dk/sw
$('#myinput').suggest({key: "<mykey>","filter": "(all type:/music/musical_group )"
})
.bind("fb-select", function(e, data) {
$.getJSON("http://ws.spotify.com/search/1/track.json?q="+search_val, function(data) {
items = [];
$.each(data["tracks"], function(key, val) {
items.push('<li class="spot"><span typeof="MusicRecording" property="track"><p>Name: <strong><span property="name">' + val["name"] + '</span></span></strong></p> <p>Album <strong>' + val.album["name"] + '</strong></p><p> Released: <strong>' + val.album["released"] +'</strong></p><p><strong><i class="icon-play-sign"></i> Start Spotify</strong></p>');
if ( key === 7 )
{
return false;
}
});
$('#spotify-div').prepend('<h3 style="border-bottom:1px solid white;">Spotify tracks</h3>');
$('#spotify').html(items.join('</li>'));
});
});
This is just a snippet of my some of my code. I run multiple getJson functions.
How can I clear/empty my result div before running the other functions?
Lots of people have explained the mechanics of clearing, which it sounds like you already understand, so perhaps the missing piece is when to do it. You probably want to clear things as the very first thing in your Freebase Suggest select callback, before you fire off any of the queries to other services like Spotify (i.e. before the first $.getJSON()).
Not related to your question, but don't forget the attribution requirement of the Freebase license (not currently provided on your web site).
EDIT: Here's your code with empty added:
$('#myinput').suggest({key: "<mykey>","filter": "(all type:/music/musical_group )"
})
.bind("fb-select", function(e, data) {
$('#spotify-div').empty(); // empty the div before fetching and adding new data
$.getJSON("http://ws.spotify.com/search/1/track.json?q="+search_val, function(data) {
items = [];
$.each(data["tracks"], function(key, val) {
items.push('<li class="spot"><span typeof="MusicRecording" property="track"><p>Name: <strong><span property="name">' + val["name"] + '</span></span></strong></p> <p>Album <strong>' + val.album["name"] + '</strong></p><p> Released: <strong>' + val.album["released"] +'</strong></p><p><strong><i class="icon-play-sign"></i> Start Spotify</strong></p>');
if ( key === 7 )
{
return false;
}
});
$('#spotify-div').prepend('<h3 style="border-bottom:1px solid white;">Spotify tracks</h3>');
$('#spotify').html(items.join('</li>'));
});
});
Select the element and put HTML blank like below
jQuery('#selector').html('');
then after apply the append jquery function on same selector like below
jQuery('#selector').append("<p>text</p>");
You can also do this by clearing the inner html of the html, with id "spotify":
$('#spotify').empty();
With jQuery there can be many ways of emptying an element of its contents and appending/prepending content.
One is .empty(); ( Documentation )
$('#spotify-div').empty().prepend('<h3>YourHTML Here</h3>');
Another is .html( [ html ] ); ( Documentation )
$('#spotify-div').html('').prepend('<h3>YourHTML Here</h3>');
If you are changing the html and not worried about keeping events, you could just pass your html through the .html( 'Your HTML' ); function
$('#spotify-div').html('<h3>YourHTML Here</h3>');
I am trying to build a table grid which represents hourly blocks for each day of the week. What I would like to then do is make each cell in the table selectable, and to check a check box if that cell is selected, or if multiple cells are selected then tick all the check boxes that each cell corresponds to. I have put together a simplified version here: http://jsfiddle.net/yxAjx/4/.
I've really got as far as putting in the selectable code -
$(function() {
$( "#selectable" ).selectable({
filter: ".block"
})
});
For example if I clicked and dragged across the first 2 cells in the 'Tue' row I would want the corresponding check boxes to be checked.
The table that contains the check boxes I have no control over as this section of html is generated from the software I am using but I have replicated the lay out of it in my example.
My Javascript and jQuery knowledge is limited so would appreciate any pointers on how to achieve this.
How about doing something like this:
$(function() {
$( "#selectable" ).selectable({
filter: ".block",
selected: function( event, ui ) {
var row = $(ui.selected).parents('tr').index(),
col = $(ui.selected).parents('td').index();
$('#checks').find('tr').eq(row)
.children('td').eq(col)
.children('input').addClass('checked').prop('checked', true);
$('#checks input:not(.checked)').prop('checked', false);
},
unselected: function( event, ui ) {
var row = $(ui.unselected).parents('tr').index(),
col = $(ui.unselected).parents('td').index();
$('#checks').find('tr').eq(row)
.children('td').eq(col)
.children('input').removeClass('checked').prop('checked', false);
}
});
$('#checks input').click(function(){
var row = $(this).parents('tr').index(),
col = $(this).parents('td').index();
if($(this).prop('checked')){
$('#selectable').find('tr').eq(row)
.children('td').eq(col)
.children('div').addClass('ui-selected');
}else{
$('#selectable').find('tr').eq(row)
.children('td').eq(col)
.children('div').removeClass('ui-selected');
}
});
});
DEMO: http://jsfiddle.net/dirtyd77/yxAjx/9/
(jQuery noob here)
Im trying to write a script which when I write <input type='checkbox'/> will automatically convert it to jQuery UI button and look like a checkBox.
Sample code so far ...
var newCheckboxID = 0;
$( "input:checkbox" ).attr('id', "cbx-" + nextCheckboxID++); // how to do that?
$( "input:checkbox" ).after("<label style='width:16px; height:16px; vertical-align:middle;'></label>");
$( "input:checkbox" ).next().attr("for", $(this).attr('id') ); // doesn't work for sure
$( "input:checkbox" ).button();
$( "input:checkbox" ).button( "option", "text", false );
$( "input:checkbox" ).attr("onclick", "$(this).button( 'option', 'icons', {primary:((this.checked)?'ui-icon-check':null),secondary:null} )");
Sorry, if it's too obvious but I've lost more than hour in that ...
EDIT
Finally did it with the old fashioned way (for the doesn't working parts).
Any comments for making it more compact and "more jQuery" would be appriciated ...
Code sample
// ---- set ids
var checkboxID = 0;
//$( "input:checkbox" ).attr('id', "cbx-" + nextCheckboxID++); // how to do that?
var cboxes = document.getElementsByTagName('input'); // <-- do this instead
for(var i=0; i<cboxes.length; i++){
if( cboxes[i].getAttribute('type')!='checkbox' ) continue;
cboxes[i].setAttribute('id', 'cbx-'+checkboxID++);}
// ---- add labels
$( "input:checkbox" ).after("<label style='width:16px; height:16px; vertical-align:middle;'></label>");
//$( "input:checkbox" ).next().attr("for", $(this).attr('id') ); // doesn't work this
for(var i=0; i<cboxes.length; i++){ // <-- do this instead
if( cboxes[i].getAttribute('type')!='checkbox' ) continue;
cboxes[i].nextSibling.setAttribute('for', cboxes[i].getAttribute('id') );}
// ---- create
$( "input:checkbox" ).button();
$( "input:checkbox" ).button( "option", "text", false );
$( "input:checkbox" ).attr("onclick", "$(this).button( 'option', 'icons', {primary:((this.checked)?'ui-icon-check':null),secondary:null} )");
Working examples:
jsFiddle (without comments)
jsFiddle (without comments with UI theme switcher!)
jsFiddle (with comments)
jsFiddle (Just for fun, uses timer and some other jQuery features, just for future reference)
jsFiddle (Just for fun, uses timer and changes UI theme every second!)
In the following, I should note 2 primary changes. I added CSS to do what you were trying to do to labels in "code" (where it really doesn't belong).
Also, I changed the HTML for "ease of jQuery" use. However, I still noted in the comments how you can easily change it back.
the HTML
<center>
<button>Create New CheckBox</button>
</center>
<hr />
<div id="CheckBoxes">
<input class="inp-checkbox" />
<input class="inp-checkbox" />
<input class="inp-checkbox" />
<input class="inp-checkbox" />
</div>
the CSS
.inp-checkbox+label {
width:16px;
height:16px;
vertical-align:middle;
}
the JavaScript/jQuery
// keep in mind, and i will explain, some of these "moving-parts" or not needed, but are added to show you the "ease" of jquery and help you see the solution
// This global function is designed simply to allow the creation of new checkboxes as you specified, however, if you won't be making check boxes at end user time, then i suggest simply moving it to within the .each statement found later on.
// Also, this could easily be written as a jQuery plugin so that you could make a "chainable" one-line call to change checkboxes to this but let's get to the nitty gritty first
function createCheckBox(ele, i) {
// First I simply create the new ID here, of course you can do this inline, but this gives us a bottleneck for possible errors
var newID = "cbx-"+i;
// below we use the param "ele" wich will be a jQuery Element object like $("#eleID")
// This gives us the "chainability" we want so we don't need to waste time writing more lines to recall our element
// You will also notice, the first thing i do is asign the "attribute" ID
ele.attr({ "id": newID })
// Here we see "chainability at work, by not closing the last line, we can move right on to the next bit of code to apply to our element
// In this case, I'm changing a "property", keep in mind this is kinda new to jQuery,
// In older versions, you would have used .attr but now jQuery distinguishes between "attributes" and "properties" on elements (note we are using "edge", aka. the latest jQuery version
.prop({ "type": "checkbox" })
// .after allows us to add an element after, but maintain our chainability so that we can continue to work on the input
// here of course, I create a NEW label and then immidiatly add its "for" attribute to relate to our input ID
.after($("<label />").attr({ for: newID }))
// I should note, by changing your CSS and/or changing input to <button>, you can ELIMINATE the previous step all together
// Now that the new label is added, lets set our input to be a button,
.button({ text: false }) // of course, icon only
// finally, let's add that click function and move on!
// again, notice jQuery's chainability allows us no need to recall our element
.click(function(e) {
// FYI, there are about a dozen ways to achieve this, but for now, I'll stick with your example as it's not far from correct
var toConsole = $(this).button("option", {
icons: {
primary: $(this)[0].checked ? "ui-icon-check" : ""
}
});
console.log(toConsole, toConsole[0].checked);
});
// Finally, for sake of consoling this new button creation and showing you how it works, I'll return our ORIGINAL (yet now changed) element
return ele;
}
$(function() {
// This .each call upon the inputs containing the class I asiged them in the html,
// Allows an easy way to edit each input and maintain a counter variable
// Thus the "i" parameter
// You could also use your ORIGINAL HTML, just change $(".inp-checkbox") to $("input:[type='checkbox']") or even $("input:checkbox")
$(".inp-checkbox").each(function(i) {
// as previously noted, we asign this function to a variable in order to get the return and console log it for your future vision!
var newCheckBox = createCheckBox($(this), i);
console.log(newCheckBox);
});
// This next button added is simply to show how you can add new buttons at end-time
// ENJOY!!!
$("button").button().on("click", function(e) {
var checkBoxCount = $("#CheckBoxes .inp-checkbox").length;
var newCheckBox = $("<input />").addClass("inp-checkbox").appendTo($("#CheckBoxes"));
createCheckBox(newCheckBox , checkBoxCount);
console.log(newCheckBox);
});
});
Update: The original intent here was to purely answer the question, which was to create a jQuery UI styled checkbox and show how jQuery can be used in multiple ways. However, a later comment queried how to include a traditional style label with it. While there are a billion options for this, I'll simply take from the above and extend.
The first option I took is pretty simple. Using jsFiddle (without comments with UI theme switcher!), I made the following changes:
the JavaScript/jQuery
// First I add a new variable.
// It will simply be for a new "wrapper" element, in which to ensure our button is encased.
// Giving this element a new class gives easy access for later CSS or Event Triggering of sub elements (like the checkbox)
var newID = "cbx-"+i,
wrapper = $('<div />', { 'class': 'ui-checkbox-wrapper' }).appendTo('#CheckBoxes');
// Then I added a line to our ele series of methods.
// This line simply append our element (checkbox) to our new wrapper
// Take Note at how I added this method at start rather than at end.
// Had I not done this, then the label would not have been wrapped!
ele.appendTo(wrapper) // <-- new line!
.attr({ "id": newID })
Then I simply added the following CSS:
#CheckBoxes .ui-button .ui-button-text {
background: #A9A9A9;
display: inline;
font-size: 16px;
left: 19px;
padding: 0;
position: relative;
text-indent: 0;
top: -4px;
}
Results!