Query(document).ready(function() {
var trCount = $('.Firsttable tr').length;
for (var i = 4; i <=4; i++) {
var $td = $('.Firsttable tr:eq(2) td:eq(' + i + ')'),
highest = 0,
lowest = 9e99;
for (var j = 1; j < trCount; j++) {
$td = $td.add('.Firsttable tr:eq(' + j + ') td:eq(' + i + ')');
}
$td.each(function(i, el){
var $el = $(el);
if (i > 0) {
var val = parseInt($el.text().replace(/[\$,]/g, ''), 10);
if (val < lowest) {
lowest = val;
$td.removeClass('low');
$el.addClass('low');
}
}
});
}
Assign ID attribute to each of your tables and write a function like this:
<script type="text/javascript">
function testTable(tableId) {
var trCount = $('#'+ tableId +' tr').length;
for (var i = 4; i <=4; i++) {
var $td = $('#'+ tableId +' tr:eq(2) td:eq(' + i + ')'),
highest = 0,
lowest = 9e99;
for (var j = 1; j < trCount; j++) {
$td = $td.add('#'+ tableId +' tr:eq(' + j + ') td:eq(' + i + ')');
}
$td.each(function(i, el){
var $el = $(el);
if (i > 0) {
var val = parseInt($el.text().replace(/[\$,]/g, ''), 10);
if (val < lowest) {
lowest = val;
$td.removeClass('low');
$el.addClass('low');
}
}
});
}
</script>
Now just call this function for every table by passing it's id,
<script type="text/javascript>
Query(document).ready(function() {
testTable('table1');
testTable('table2');
}
</script>
Hope it helps, thanks.
Related
Is there a way to get the 'username' and 'questionid' variable's value in my send() function like how I did with inputText?
var username;
var questionid;
function renderHTML(data) {
var htmlString = "";
var username = data[0].username;
//var examid = data[1].examid;
var questionid = data[2].questionid;
for (var i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].questionid + "." + "\n" + "Question: " + data[i].question + "\n" + "<input type='text'>";
htmlString += '</p>';
}
response.insertAdjacentHTML('beforeend', htmlString);
}
function send() {
var inputText = document.querySelectorAll("input[type='text']");
var data = [];
for (var index = 0; index < inputText.length; index++) {
input = inputText[index].value;
data.push({
'text': input
});
}
console.log(data);
You do not need var before username and questionid in your renderHTML function, as they have already been defined:
var username;
var questionid;
function renderHTML(data) {
var htmlString = "";
username = data[0].username;
//var examid = data[1].examid;
questionid = data[2].questionid;
for (var i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].questionid + "." + "\n" + "Question: " + data[i].question + "\n" + "<input type='text'>";
htmlString += '</p>';
}
response.insertAdjacentHTML('beforeend', htmlString);
}
function send() {
var inputText = document.querySelectorAll("input[type='text']");
var data = [];
for (var index = 0; index < inputText.length; index++) {
input = inputText[index].value;
data.push({
'text': input
});
}
console.log(data);
I am been trying to create a html table that is populated by objects.
The table was supposed to be selectable by row (via hover), when the row was hovered over a function ran.
The table headers are in an array:
var topTitles = ["Type","Origin","Destination","T","A","G"];
all the data are sitting inside arrays,
var Type = [];
var Origin = [];
var Destination = [];
var T = [];
var A = [];
var G = [];
I tried to modify an example piece of code, but it was very difficult to conceptualize it and place it into a programatic solution. What is an easy way to map such data directly into a interactive table.
function createTable() {
var table = document.getElementById('matrix');
var tr = addRow(table);
for (var j = 0; j < 6; j++) {
var td = addElement(tr);
td.setAttribute("class", "headers");
td.appendChild(document.createTextNode(topTitles[j]));
}
for (var i = 0; i < origins.length; i++) {
var tr = addRow(table);
var td = addElement(tr);
td.setAttribute("class", "origin");
td.appendChild(document.createTextNode(mode[i]));
for (var j = 0; j < topTitles.length; j++) {
var td = addElement(tr, 'element-' + i + '-' + j);
td.onmouseover = getRouteFunction(i,j);
td.onclick = getRouteFunction(i,j);
}
}
}
function populateTable(rows) {
for (var i = 0; i < rows.length; i++) {
for (var j = 0; j < rows[i].elements.length; j++) {
var distance = rows[i].elements[j].distance.text;
var duration = rows[i].elements[j].duration.text;
var td = document.getElementById('element-' + i + '-' + j);
td.innerHTML = origins[i] + "<br/>" + destinations[j];
}
}
}
if (highlightedCell) {
highlightedCell.style.backgroundColor="#ffffff";
}
highlightedCell = document.getElementById('element-' + i + '-' + j);
highlightedCell.style.backgroundColor="#e0ffff";
showValues();
}
This is probably the easiest way I could think of building the table without changing your data structure and make it very clear where all the data is coming from. It is defiantly not the best code, but it should work for your situation.
CodePen
var topTitles = ["Type","Origin","Destination","T","A","G"];
var Type = ["Type1", "type2", "type3"];
var Origin = ["Origin1", "origin2", "origin3"];
var Destination = ["Destination1", "Destination2", "dest3"];
var T = ["t1", "t2","T3"];
var A = ["steaksauce", "a2", "a3"];
var G = ["G1", "G2", "G3"];
var appendString = [];
for(var i =0; i < topTitles.length; i++){
if(!i){
appendString.push("<tr><td>" + topTitles[i] + "</td>");
}
else if(i === topTitles.length -1){
appendString.push("<td>" + topTitles[i] + "</td></tr>");
}
else{
appendString.push("<td>" + topTitles[i] + "</td>");
}
}
for(var i =0; i < Type.length; i++){
appendString.push("<tr><td>" + Type[i] + "</td><td>" + Origin[i] + "</td><td>" + Destination[i] + "</td><td>" + T[i] + "</td><td>" + A[i] + "</td><td>" + G[i] + "</td></tr>");
}
var table = document.getElementById('table');
table.innerHTML = appendString.join('');
Can somebody please tell me what is wrong with the JavaScript in this code? It said "Unexpected end of input", but I do not see any errors. All my statements seem to be ended at some point, and every syntax checker says that no errors were detected.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<title>Slide Editor</title>
<style>
#font-face {
font-family: SegoeUILight;
src: url(Segoe_UI_Light.ttf);
}
* {
font-family: SegoeUILight;
}
</style>
<script src="Slide/RevealJS/lib/js/html5shiv.js"></script>
<script src="Slide/RevealJS/lib/js/head.min.js"></script>
</head>
<body onload="editSlideshow()">
<div id="sl">
<span id="sls"></span>
</div>
<span id="slt"></span>
<div id="editor">
</div>
<script>
function getURLParameters(paramName) {
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0) {
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i = 0; i < arrURLParams.length; i++) {
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i = 0; i < arrURLParams.length; i++) {
if (arrParamNames[i] == paramName) {
//alert("Parameter:" + arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
var name = getURLParameters("show");
var slideCount = 1;
function editSlideshow() {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
$("#sls").append('<button onclick = "loadSlide\'1\')" id = "slide_1">Slide 1</button>');
$("#sl").append('button onclick = "newSlide()">New Slide</button>');
slideCount = 1;
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
slideCount = textArray.length;
var slideCnt = textArray.length - 1;
for (var i = 0; i <= slideCnt; i++) {
$("#sls").append('<button onclick = "loadSlide\'' + (i + 1) + '\')" id = "slide_' + (i + 1) + '">Slide ' + (i + 1) + '</button>');
};
$("sl").append('<button onclick = "newSlide()">New Slide</button>');
};
};
function loadSlide(num) {
var array = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
if (array == null) {
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
} else if (array[num - 1] == null) {
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
} else {
var slideArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
var text = slideArray[num - 1];
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("editTxt").value = text;
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
};
};
function saveSlide(num) {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
var text = document.getElementById("editTxt").value;
var textArray = new Array();
textArray[num - 1] = text;
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
var text = document.getElementById("editTxt").value;
textArray[num - 1] = text;
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
};
};
function newSlide() {
var nextSlide = slideCount + 1;
$("#sls").append('<button onclick = "loadSlide(\'' + nextSlide + '\')" id = "slide_' + nextSlide.toString() + '">Slide ' + nextSlide.toString() + '</button>');
slideCount = nextSlide;
};
function deleteSlide(num) {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
if (num !== "1") {
$("#slide_" + num).remove();
document.getElementById("editor").innerHTML = "";
document.getElementById("slt").innerHTML = "";
slideCount = slideCount - 1;
location.reload();
} else {
alert("The first slide cannot be deleted.");
};
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
if (num !== "1") {
$("#slide_" + num).remove();
document.getElementById("editor").innerHTML = "";
document.getElementById("slt").innerHTML = "";
slideCount = slideCount - 1;
textArray.splice((num - 1), 1);
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
location.reload();
} else {
alert("The first slide cannot be deleted.");
};
};
};
</script>
</body>
</html>
You've gotten the punctuation wrong in more than one of your onclick attributes, for instance here:
$("#sls").append('<button onclick = "loadSlide\'1\')" id = "slide_1">Slide 1</button>');
It's missing the opening parenthesis. The reason syntax checks don't immediately catch this is because you're putting code inside a string. Which you should not do.
Since you're using jQuery, how about using .click(function() { ... }) instead of inline attributes? Just be careful to get your captured variables correct.
The problem at line 63
$("#sl").append('button onclick = "newSlide()">New Slide</button>');
Should be:
$("#sl").append('<button onclick = "newSlide()">New Slide</button>');
I created a dynamic table that contains 20 rows and 2 columns. this is my code:
function createTblBtnClick() {
var tbl = document.createElement("table");
tbl.setAttribute("id", "myTable");
tbl.setAttribute("dir", "rtl");
tbl.cellPadding = 0;
tbl.cellSpacing = 0;
for (i = 0; i < rowNum; i++) {
var row = tbl.insertRow(-1);
for (j = 0; j < colNum; j++) {
var cell = row.insertCell(-1);
cell.setAttribute("id", "cell" + i.toString() + "-" + j.toString());
}
}
document.getElementById("MyTablePanel").innerHTML = "";
document.getElementById("MyTablePanel").appendChild(tbl);
for (i = 0; i < rowNum; i++) {
for (j = 0; j < colNum; j++) {
var srt = "<a href='javascript:select(" + i.toString() + "," + j.toString() + ")' ><div id='div-" + i.toString() + "-" + j.toString() + "'> </div></a>";
document.getElementById("cell" + i.toString() + "-" + j.toString()).innerHTML = srt;
}
}
}
Now I want to add another table in any of my cells. In fact I want to divide each of my cells to 2. How can I do it?
I test below code but it creates 4 column in a row :
function createTblBtnClick() {
var tbl = document.createElement("table");
var tb2 = document.createElement("table");
tbl.setAttribute("id", "myTable");
tbl.setAttribute("dir", "rtl");
tbl.cellPadding = 0;
tbl.cellSpacing = 0;
tb2.setAttribute("id", "myTable1");
//tbl.setAttribute("dir", "rtl");
tb2.cellPadding = 0;
tb2.cellSpacing = 0;
var inner_tb = 0;
for (i = 0; i < rowNum; i++) {
var row = tbl.insertRow(-1);
for (j = 0; j < colNum; j++) {
var cell = row.insertCell(-1);
cell.setAttribute("id", "cell" + i.toString() + "-" + j.toString());
}
}
document.getElementById("MyTablePanel").innerHTML = "";
document.getElementById("MyTablePanel").appendChild(tbl);
////////////////////////////////////////////////////////
var row1 = tb2.insertRow(-1);
for (inner_tb = 0; inner_tb < 2; inner_tb++) {
var cell1 = row.insertCell(-1);
cell.setAttribute("id", "in_cell " + inner_tb.toString());
}
document.getElementById("cell" + i.toString() + "-" + j.toString()).innerHTML = "";
document.getElementById("cell" + i.toString() + "-" + j.toString()).appendChild(tb2);
///////////////////////////////////////////////////////////////
for (i = 0; i < rowNum; i++) {
for (j = 0; j < colNum; j++) {
var srt = "<a href='javascript:select(" + i.toString() + "," + j.toString() + ")' ><div id='div-" + i.toString() + "-" + j.toString() + "'> </div></a>";
document.getElementById("cell" + i.toString() + "-" + j.toString()).innerHTML = srt;
}
}
}
Do exactly the same logic, but append the table to a cell reference.
var innerTbl = document.createElement("table");
//Populate the table...
//With the table populated, append it in the cell of the outertable.
cell.appendChild(innerTbl);
I think this might be what you're trying to do:
http://jsfiddle.net/mPwpq/1/
function createTblBtnClick() {
var rowNum = 20;
var colNum = 2;
var tbl = document.createElement("table");
tbl.setAttribute("id", "myTable");
tbl.setAttribute("dir", "rtl");
tbl.cellPadding = 0;
tbl.cellSpacing = 0;
for (i = 0; i < rowNum; i++) {
var row = tbl.insertRow(-1);
for (j = 0; j < colNum; j++) {
var cell = row.insertCell(-1);
cell.setAttribute("id", "cell" + i.toString() + "-" + j.toString());
// Add inner table with two columns
var innerTbl = document.createElement("table");
innerTbl.innerHTML = '<tr><td>A</td><td>B</td></tr>';
cell.appendChild(innerTbl);
}
}
document.getElementById("MyTablePanel").innerHTML = "";
document.getElementById("MyTablePanel").appendChild(tbl);
}
just a suggestion. Rather than using javascript for doing creating table, why not create the table in the HTML. Get that table in a var using Document.getElementByID. create new string variable like "thisRow" and add the HTML code in the string of the variable like
thisRow += "rowcellinner table"
and then use .append(thisRow);
you can assign the value to thisRow variable in each counter of the loop and append it to table. I find this easier to do.
The following Jquery code works well in Firefox but throws exception in IE. Please help. The following code will render a multi select box where you can drag and drop values from one box to other. The code when run in IE throws an object expected expception. As it in inside a large page, the actual place of bug can not be identified.
$(document).ready(function() {
//adding combo box
$(".combo").each(function() {
var name = "to" + $(this).attr('name');
var $sel = $("<select>").addClass("multi_select");
$sel.addClass("combo2");
$sel.attr('id', $(this).attr('id') + "_rec");
$(this).after($sel);
});
$(".multi_select").hide();
var $tab;
var i = 0;
var temp = 0;
//creating different div's to accomodate different elements
$(".multi_select").each(function() {
var $cont = $("#container");
var $input;
if ($(this).hasClass("combo") || $(this).hasClass("combo2")) {
var $col = null;
if ($(this).hasClass("combo")) {
$tab = $("<table>");
$cont = ($tab).appendTo($cont);
var idT = $(this).attr('id');
var $row = $("<tr id='" + idT + "_row1'>").appendTo($tab);
$col = $("<td id='" + idT + "_col1'>").appendTo($row);
$input = $("<input class='searchOpt'></input><img src='images/add.png' class='arrow1'/> ");
$("<div>").addClass('ip_outer_container combo').attr('id', $(this).attr('id') + "out_div").append("<h3 class='header_select'>Tasks</h3>").appendTo($col);
($row).after("<tr><td></td><td><textarea name='" + $(this).attr("name") + "Text' id='" + $(this).attr("id") + "Text'></textarea> </td></tr>");
$cont = $tab;
} else {
var idTm = $(this).attr('id');
var $row2 = $("<tr id='" + idTm + "_row2'>").appendTo($tab);
var $col2 = $("<td id='" + idTm + "_col2'>").appendTo($row2);
$input = $("<input class='searchOpt'></input>");
$("<div>").addClass('ip_outer_container combo2').attr('id', $(this).attr('id') + "out_div").append("<h3 class='header_select'>Tasks</h3>").appendTo($col2);
}
} else {
$("<div>").addClass('ip_outer_container' + classSelect).attr('id', $(this).attr('id') + "out_div").append("<h3 class='header_select'>Tasks</h3>").appendTo($cont);
}
$("<div>").addClass('outer_container').attr('id', $(this).attr('id') + "_div").appendTo('#' + $(this).attr('id') + "out_div");
$($input).appendTo("#" + $(this).attr('id') + "out_div");
});
//adding options from select box to accomodate different //elements
$(".multi_select option").each(function() {
$(this).attr('id', $(this).parent().attr('id') + "option_" + i);
var val = $(this).val().replace("#comment#", "");
var $d = $("<div class='multi_select_div'>" + val + "</div>").attr('id', $(this).parent().attr('id') + 'option_div_' + i);
$d.appendTo("#" + $(this).parent().attr('id') + "_div");
i++;
});
//delete function
$(".delete").click(function() {
$(this).parent().remove();
});
//input
$(".searchOpt").keyup(function() {
$(this).prev().children().show();
var val = $(this).val();
if (val != "") {
var selId = $(this).prev().attr('id');
selId = selId.replace("_div", "option_div");
$(this).prev().children().not("div[id^=" + selId + "]:contains(" + val + ")").hide();
//var $d=$('div[id^="multi_select_senoption_div"]');
//$('div[id^="multi_select_senoption_div"]').not('div[id^="multi_select_senoption_div"]:contains("xls")').hide();
}
});
var optionId = 0;
$(".arrow1").click(function() {
var divId = $(this).parent().attr("id");
divId = divId.replace("out_div", "");
var textValue = "#comment#" + $("#" + divId + "Text").val();
var selToId = divId + "_rec";
$("#" + divId + " option[selected='selected']").each(function() {
var idOpt = $("#" + selToId).attr("id") + "option_" + optionId;
$opt = $("<option>");
$opt.attr("id", idOpt).attr("value", $(this).val() + textValue);
$("#" + selToId).append($opt);
var value = $(this).val().replace("#comment#", "");
var divId = $("#" + selToId).attr('id') + 'option_div_' + optionId;
var $de = $("<div class='multi_select_div'><img class='delete' src='images/delete.png'></img>" + value + "</div>").attr('id', divId);
$de.appendTo("#" + $("#" + selToId).attr('id') + "_div");
$("#" + divId).bind("click", handler);
var optId = divToOption($(this).attr("id"));
var optValue = $(optId).val();
var comment = optValue.substring(optValue.indexOf("#comment#") + 9);
$("#" + divId).attr("title", textValue.replace("#comment#", ""));
//$("#"+divId).bind("mouseenter",handler2);
//$("#"+divId).bind("mouseleave",handler3);
$(".delete").bind("click", handler1);
optionId++;
});
// function code
//
});
$(".multi_select_div").click(function() {
var id = divToOption($(this).attr('id'));
var selected = $(id + "[selected]");
if (selected.length > 0) {
$(id).attr('selected', false);
var cssObj = {
'background-color': 'black'
};
$(this).css(cssObj);
}
else {
$(id).attr('selected', 'selected');
var cssObj = {
'background-color': 'orange'
};
$(this).css(cssObj);
}
});
function handler(event) {
var id = divToOption($(this).attr('id'));
var selected = $(id + "[selected]");
if (selected.length > 0) {
$(id).attr('selected', false);
var cssObj = {
'background-color': 'black'
};
$(this).css(cssObj);
}
else {
$(id).attr('selected', 'selected');
var cssObj = {
'background-color': 'orange'
};
$(this).css(cssObj);
}
}
function handler1(event) {
$(this).parent().remove();
}
function handler2(event) {
var optId = divToOption($(this).attr("id"));
var optValue = $(optId).val();
var comment = optValue.substring(optValue.indexOf("#comment#") + 9);
var pos = $(this).position();
var cssObj = {
top: pos.top - 100,
left: pos.left + 200
};
var $divImg = $("<td>");
var $divCl = $("<div class='comment'>" + comment + "</div>").css(cssObj);
$divImg.append($divCl);
$(this).parent().parent().parent().parent().append($divImg);
}
function handler3(event) {
$(".comment").remove();
}
});
function optionToDiv(option) {
var id_div = option.replace('option_', 'option_div_');
id_div = "#" + id_div;
return id_div;
}
function divToOption(div) {
var id_opt = div.replace('div_', '');
id_opt = "#" + id_opt;
return id_opt;
}
IE browsers do not support indexOf for an array, which arises issue with javascript.
Add the below javascript in the head of the page, it might resolve your issue:
//
// IE browsers do not support indexOf method for an Array. Hence
// we add it below after performing the check on the existence of
// the same.
//
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function (obj, start)
{
for (var i = (start || 0), j = this.length; i < j; i++)
{
if (this[i] === obj)
{
return i;
}
}
return -1;
};
}