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!
Related
I want to use the currently selected text in the office document to be replaced by the same selected text but surrounded with html. Effectively adding a hyperlink to the current selection.
I first read the text property of the selection
var objRange = objContext.document.getSelection();
objRange.load('text');
followed by
return objContext.sync().then(function(){
var strSelection = objRange.text;
objRange.insertHtml(
"<a href='" + decodeURIComponent(strHyperlink) + "'>" + strSelection + "</a>",
Word.InsertLocation.replace
);
return objContext.sync().then(function(){
objDialog.close();
});
});
I need a sync to read the text and then another one to write the updated text back into the document after that I close a dialog. But this sometimes causes the html to get written into the document twice. Is there a better way of doing this instead of with double context syncs?
To answer your question, if you need to read the text and then write into a different context, you'll need two syncs.
But you might take a look at the Range.hyperlink property, which is writeable. I don't know if it'll give you a way to avoid two syncs, but is intended for what you seem to be using insertHtml to do.
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
})
I'm making a very simple minigame which idea is to pick the proper color of the figure you've seen for about a second or two by clicking one of the four divs with the id's circle1, circle2 etc. with the specific colors:
var odpowiedz_kolor = $('<div class="label id="gra">Jaki kolor miał następujący kształt?</br></br><ul class="inline">'+
'<div class="odpowiedz_pojemnik" id="' + wylosowane[losowa_z_wylosowanych_figur].figura + '"> </div></br></br>'+
'<ul class="inline">'+
'<li><div class="kolo" id="kolo1"> </div></li>'+
'<li><div class="kolo" id="kolo2"> </div></li>'+
'<li><div class="kolo" id="kolo3"> </div></li>'+
'<li><div class="kolo" id="kolo4"> </div></li>'+
'</ul></div>');
I've cut out the unnecessary code...
$('#kolo1').css('background-color', wylosowane[0].kolor);
$('#kolo2').css('background-color', wylosowane[1].kolor);
$('#kolo3').css('background-color', wylosowane[2].kolor);
$('#kolo4').css('background-color', wylosowane[3].kolor);
$(".kolo").on('click', function(){
var color = $('.kolo').find('#kolo').css('background-color');
I've set the colors as seen above. Now's the question how to retrieve the according colors 'cause I'm stuck on the click handler. I'd appreciate even the ugly but working solutions.
The scenario is:
you see 4 different figures with different colors for a couple of seconds
you now have to decide which one was it (if pick good/bad then...)
Thank you in advance.
You probably want to know the color of the figure that you just clicked, so I suggest you made this :
$(".kolo").on('click', function(){
var color = $(this).css('background-color');
}
JsFiddle : http://jsfiddle.net/F3HB5/
EDIT :
Based on your code, I have updated your jsFiddle to this one : http://jsfiddle.net/8LFR7/3/.
There were 2 main errors :
when you want to target an id, you have to put a # before the id -> $("#" + wylosowane[losowa_z_wylosowanych_figur].figura).css('background-color').
As you remove your figure before the test, you have to capture the color BEFORE you remove it and save it in some variable : here I have put it at the beginning of the setTimeout block : var targetColor = $("#" + wylosowane[losowa_z_wylosowanych_figur].figura).css('background-color');
Firstly a friendly advice, whichever native language you belong to, please use English for your code.
Now your solution: Well you need to match the background-color for the clicked circle with the triangle, so you can do the following to achieve this:
$(".kolo").on('click', function(event){
var id = event.target.id; // For the id, but that does not matter, you can get it using the class also or this
if($(id).css('background-color') == $('.odpowiedz_pojemnik').css('background-color')){
alert('Good!');
}
else{
alert('Bad!');
}
}
IE is giving me an error (Error: Invalid target element for this operation.) when trying to execute this code:
var d1 = document.getElementById( name + '-body');
d1.insertAdjacentHTML('beforeend', html );
Without having to put the entire function in here, the point of it is to add some text inputs dynamically when a user clicks a button. I did a bit of searching and found many statements that insertAdjacentHTML doesn't work right within tables, which is what I need it to do.
Is there a workaround for this?
Edit: Here is the html I am trying to insert. If you want I can post the generated html from Chrome also.
"<tr id=\"node-" + counter + "\">
<td>
<textarea onclick=\"Common.removeInstructions(id)\" name=\"on\" id=\"action-" + counter + "\" wrap=\"soft\" cols=\"35\" rows=\"4\" style=\"resize: none; overflow: hidden;\">
Please limit responses to 150 characters. Blank fields will be ignored.
</textarea>
</td>
<td>
<input classname=\"TextInput\" id=\"actionDate-" + counter + "\" newline=\"1\" style=\"width: 100px;\" class=\"TextInput\" assemblers=\"jaba.ui.input.TextInput\" jaba-pagerowindex=\"1\"/>
</td>
</tr>"
IE often doesn't allow you to dynamically add table rows/cells.
Pre-creating the rows/cells which you want added with display:none, then changing their innerHTML and display when needed is an useful workaround for that.
Adding Fabrício Matté as an answer so I can accept it.
If you'd show us the generated HTML and what you're trying to do, it'd be much easier to reply. Anyway, I've had a problem inserting rows/cells in a table on IE before, my solution was pre-creating the rows/cells with display:none when the table is created, then changing the 's innerHTML together with their display.
I have the following markup which I do not have direct access to...
<iimg src="/v/vspfiles/templates/100/images/buttons/btn_quantitydiscounts.gif" border="0" align="absmiddle">
I need to "rewrite" the above as follows...
A few things to point out is that the title is coming from a variable escape(global_Current_ProductCode) variable=productcode
The height, width, price and product id used in the second markup must be from the first markup. Note that these change depending on the product page loaded. These are not constants.
I would guess the first thing to do was to add the thickbox class. Then I am lost as to what to do next.
Basically I need to open up an thickbox iframe with the modified markup.
Register and ask again in a more parsable way.
the second part was as follows...
<aa href="/BulkDiscounts.asp?ProductID=318&ProductCode=LB30X40ES&Orig_Price=22.95&keepThis=true&TB_iframe=true&height=300&width=330"
title="LB30X40ES Laundry Bags" class="thickbox"> img border="0" align="absmiddle"
src="/v/vspfiles/templates/100/images/buttons/btn_quantitydiscounts.gif">
Untested - should get you close:
var re = /.*?\(('.*?'),.*?'(.*?)'.*(width=\d*).*(height=\d*).*/;
var match = $("a").attr("onclick").match(re);
eval("var url = " + match[1]);
$('a').unbind('click').click(function() {
TB_show(match[2], url + "&keepThis=true&TB_iframe=true&" + match[3] + "&" + match[4]);
});