build a list with Javascript append - javascript

I want to build a list with a Javascript that uses Append function.
I have a index.php file, script.js file and a search.php file that makes the mysql query.
I got it all to work but the layout is not the best. So i wounder how to make the layout better.
I want it to be displayed as a list this should be done with CSS or table?
Right now it just shows up like this 414622570992222
this.number=70992222
this.code=4146225
So what i want it to like like is a list without boarders like this (but no borders).
----------------------
| Number | Code |
----------------------
| 70992222 | 4146225 |
----------------------
Here is some code from my script.js file.
$.each(data.results, function(){
//Give the list element a rel with the data results ID incase we want to act on this later, like selecting from the list
$('#results-list').append("<li rel='" + this.number + "'>" + this.code + this.number + "</li>");
And this is the display line in my index.php file
<div id='results-holder'>
<ul id='results-list'>

replace your ul tag with a table
<table id='results-list'></table>
then append table headings and rows to your table with jquery.
$('#results-list').append("<tr><th>number</th><th>code</th></tr>");
$('#results-list').append("<tr><td>"+ this.number + "</td><td>" + this.code + "</td></tr>");
more info about html tables can be found here:
http://www.w3schools.com/html/html_tables.asp

It's better as table.
here is working example with tables.
just design it as you want.
Html
<div id='results-holder'>
<table id='results-list'>
<tr>
<th>
number
</th>
<th>
code
</th>
</tr>
</table>
</div>
Javascript
$(document).ready(function(){
$.each(data.results, function() {
$('#results-list').append("<tr><td rel='" + this.number + "'>" + this.code + "</td><td>" + this.number + "</td></tr>");
});
});
jsFiddle

this should be done with CSS or table?
These are not mutually exclusive. <table> is an HTML element, which like other elements you should choose if it has semantic purpose, i.e. if the element contains data that pertains to what the element stands for. Then you use CSS to make it look the way you want to.
If you have a paragraph of text that needs to be very huge, it's still a paragraph, so you put it in a <p> and then you style it with CSS to look big. Putting it in a <h1> element would also make it big, but that element is for titles.
If you have tabular data, like showing the contents of a database table you should use a <table>. Then you use CSS to hide the borders.
I'd do something like this:
$.each(data.results, function(){
$('#results-list').append("<tr><td>" + this.code + "'</td><td>" + this.number + "</td></tr>");
});
And make the #results-list a <table>

Related

Creating an html template for an object

I'm creating a web page that should be able to add student courses to a list/grid or whatever kind of html element. I haven't decided what would work best.
I find the courses by using the bootstrap3-typeahead.js and when selecting one of those I want to "add" a "course item" to some sort of basket - like a shopping basket. I have heard that one can use html templates for this, but I can't seem to find any good examples by searching google or in here.
Right now I have loaded a list (1360 items) of objects with attributes:
course id (ranging from 1-1360)
course number
course name
course teacher
course keywords
I want this course item to be an overview of the course. I picture something like this:
Right now I just use the following to add them as <li>elements to a <ul> I've made.
$("#basket").append('<li>' + item.name + ', ' + item.number + '</li>');
Which results in this:
I imagined being able to apply the variables to some sort of template which would be done for every single item that was added, e.i. $("#basket").loadTemplate(<template name>, item.name, item.number etc..)
In short:
I want to know if there's some way of using html templates to create elements that I can control with javascript/JQuery and if possible how this is done?
Thanks!
Yes, you can create a "template" function
//example
var myBox = createBox("computer science", "0122", "programming, databases")
$(".myCourseList").append(myBox)
function createBox(courseName, courseId, courseClasses){
var html = "";
html += "<div class='courseBox'>" +
"<p class='courseName'>" + courseName + "</p>" +
"<p class='courseId'>" + courseId+ "</p>" +
"<p class='courseClasses'>" + courseClasses + "</p>" +
"<p class='xOut'>X</p>" +
"</div>"
return html;
}
Of course you need an entire library for the dragging stuff, but take that as a different task for later.
I've ignored CSS styling, but you would do CSS like normally. just write classes corresponding with those in your code.
Now, when you dynamically create elements, it's important you delegate your bindings.
$(".myCourseList").on("click", "p.xOut", function(){
$(this).closest(".courseBox").remove(); //edited this line
})

upgrading javascript that adds a link to a field

I am trying to change the Sales Stage field label to a hyperlink to pop up a new browser window.
Currently I have a form with a Sales Stage field that has a drop down::
The underlying HTML:
<td title="Select the sales process stage for the opportunity to indicate the probability of closing the opportunity." class="ms-crm-ReadField-Normal ms-crm-FieldLabel-LeftAlign" id="salesstagecode_c"><span class="ms-crm-InlineEditLabel"><span class="ms-crm-InlineEditLabelText" style="text-align: left; max-width: 115px;">Sales Stage</span><div class="ms-crm-Inline-GradientMask" style="display: none;">
</div></span></td>
or perhaps better formatted:
The function that I used previously worked on an older version of the form:
function csjs_AddHyperlinkToLabel(sFieldId, sURL, sWindowOptions) {
    var sCurrentLabel = $("label[for='" + sFieldId + "']").html();
    $("label[for='" + sFieldId + "']").html("" + sCurrentLabel + "");
}
the function above worked on a form with the following html::
What changes would be required to the javascript to change the Sales Stage field label to a hyperlink to pop up a new browser window?
Though I'd be very grateful for a solution, I'm looking for guidance on how to accomplish this. Thank you for your attention and time.
Unfortunately, the solutions below did not work. I ran this through the debugger and here's what I got http://screencast.com/t/fT6tHvXZzvc
The issue here is that we are passing “salesstagecode” to this function:
csjs_AddHyperlinkToLabel("salesstagecode", sPageURL, sWindowFeatures);
and this turns out to be NULL:
var sCurrentLabel = $("label[for='" + sFieldId + "']").html();
*
The issue is that Microsoft changed the way the forms are rendered and
the HTML of the rendered page will no longer work with the way the
function was written. The label is now in a span tag instead of a
label tag. I don't know if there is a way to identify that span and
change the contents to have new HTML to make the text link.
*
How do you update a span tag?
You need to add target="_blank" attribute in your hyperlink markup.
Simple:
change
.... onclick=\"window.open('" + sURL + "', null, '" ....
to
.... onclick=\"window.open('" + sURL + "', '_blank', '" ....

Initializing isotope with dynamic data json

I have searched around but no help. My issue is I am using the isotope jQuery library to show data (of course) and I am trying to do this by using a dynamic json dataset. I placed the data in a .json file and I'm reading it in and parsing information, then placing that info in divs under my container div like so:
$('#infoContainer').append('<div class="hospital ' + $number + '"><p>' + i + '<br />' + hospital.address + '<br />' + hospital.citystatezip + '</p></div>');
Of course that portion is in an .each() function for each hospital. My problem is that the initialization code won't show the dynamic divs like it shows when you manually type them. I'm using what is given on the isotope website:
$('#infoContainer').isotope({
itemSelector: '.hospital'
});
Any ideas?
The answer is found on this question: JavaScript Isotope- How to manage dynamic data set (re-initialize Isotope)
I needed to use the insert method.

jQuery Readability: insert table inside <li> element

I hope to get some advise about how to write the javascript and jQuery code more beautiful and gain more readability.
In this case, I hope to insert table inside a list element. Both list and table are added dynamic by using script.
I have some code like this:
$('#Items').append("<ul></ul>");
var car_index;
var photo_index;
var lot_index;
for (car_index = 0; car_index < cars.length; car_index++)
{
lot_index = car_index + 1;
//From here, I thought the code is really ugly...though it works.
//I can't image that I will need to adde 3 rows with 6 cols into the table by using this way
//Also each col may has their own style need to be assigned....
//Any advise??
$('#Items ul').append("<li id='r_" + car_index +"'></li>");
$('#r_' + car_index).append("<table cellspacing='2' cellpadding='0'><tr><td width='50' align='left' style='font-size:10pt; font-weight:bold'>Lot " + lot_index +"</td></tr></table>");
}
As I write in the comments of above code. I could use append method and put a lot of HTML code in there. However it really looks ugly... and in the above example, I just added one row in the list. In the final goal, I have to add three rows, with about 6 cells. Each cell will have their own style set for the content. It will really be a mess.
Any advice will be appreciate! Thank you!
Perhaps use templating via either Mustache or jQuery.
See more: What Javascript Template Engines you recommend?
try this, coz
$('#Items ul').append("<li id='r_" + car_index +"'></li>); is not enclosed between " "
$('#Items ul').append("<li id='r_"+car_index+"'></li>");
$('#r_' + car_index).append("<table cellspacing='2' cellpadding='0'><tr><td width='50' align='left' style='font-size:10pt; font-weight:bold'>Lot " + lot_index +"</td></tr></table>");
}
Alright...After some thought, I find a way which will be more clear to write this kind of code. I'm not sure if this is the goog choice since it will require more work...but I feel it is better to write this way.
The idea is really simple, create object to store the HTML tags which will fixed for every block. As my example, it is a table will repeated every time a list will be added. So why not store all fixed table tags and their style attribute into one array like object?
var unit =
{
table_header : "<table border = '1'>",
row_1_col_1 : "<tr><td>Lot ",
row_1_col_2 : "</td><td><a class='addto' href='#'>Add to like</a>",
row_2_col_1 : "</td></tr><tr><td>",
row_2_col_2 : "</td><td><img src='",
row_3 : "'></td></tr><tr><td>",
table_end : "</td></tr></table><hr />"
};
Make this variable global, than when you need to add table, the original code:
$('#r_' + car_index).append("<table cellspacing='2' cellpadding='0'><tr><td width='50' align='left' style='font-size:10pt; font-weight:bold'>Lot " + lot_index +"</td></tr></table>");
Will become like this:
$('#r_' + car_index).append(unit['table_header'] +
unit['row_1_col_1'] + "Content in cell 1" +
unit['row_1_col_2'] + "Content in cell 2" +
unit['row_2_col_1'] + "Content in cell 3" +
unit['row_2_col_2'] + "Content in cell 4" +
unit['row_3'] + unit['table_end']);
Just be careful about double quote sign and single quote sign, and also, the array's index need to be quoted(see javascript array's use for detail if you got problem).
I think the advantage of this method is much more easy to modify the table. Add row, change content, or change style make much more easy since it use the single object.
I also not sure if this is a good way or not, hope to hear more about your thought! Thank you!

How to bind events to dynamically created JQuery DOM elements

I'm having trouble referencing an object from within the plugin I'm attempting to make.
The plugin is assosciated with a div container.
When the dom is ready it loads in startup defaults - creates its own div with id's it knows and an un ordered list. I can add list items and they work correctly using $this.append(..). However I want to add a feature where a click on an individual list item does something.. for now alert will suffice.
Normally I would be able to do:
$("#myId").click(function(){...
How would i add such functionality to a plugin?
I want that action set by the plugin itself, so clicking on list items created by the plugin are already attached to some functionality which I have written into the jquery plugin.
Based on your comment, you could store the new tab in a variable:
var newTab = $("<li id='tab#" + o.tabCount + "' myTabPane='" +
o.tabId + o.tabCount + "' class='tab'><h3>Tab " + o.tabCount
+ "</h3></li>");
$('#' + o.tabListId).append(newTab);
newTab.click(function() {
var paneId = '#' + $(this).attr('myTabPane');
$(paneId).siblings().hide();
$(paneId).show();
});
Link to working example at jsfiddle.
By the way, your original script had the second ' in the wrong place:
$("<li id='tab#'" + o.tabCount + " class='tab'><h3>Tab "
^^^
You would want to reference them after doing the append by tag name not by ID.
$(this).find("li").click(function(){ /* do work */});
If you absolutely have to reference it by ID you can do:
$(this).find("li").each(function(){
var id = $(this).attr("id");
/* do work */
});

Categories