Dynamically created HTML table opens new page - javascript

I've got a code, a math table coder actually.. If anybody presses the button, the function is called and is running.. But when i click the button, the table is coming on a new page instead in the same page..
<!doctype html>
<html>
<head>
<title>Tafel Trainer</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<section id="content">
<p>Wilt u de tafels leren? Klik op de knop oefenen</p>
<button id="oefenen" name="oefenen" value="oefenen" onclick='oefenen()';>Tafel oefenen!</button>
<div id="1">
<script type='text/javascript'>
function oefenen(){
var num = prompt("Zet een cijfer neer", "0");
var num1 = parseInt(num);
for(i= 1; i< 11; i++) {
document.writeln("<table border='1'><tr><td>" + i + " x " + num1 + " = " + i * num1 + "<br/></td></tr></table>");
}
}
</script>
</div>
</section>
</body>
</html>
I've already tried to do it with document.getElementByID('div1').innerHTML = i; But that code also didn't work, im sure its a beginners fault but what :)?
Thanks in advance!

You will have a lot more control over what you are doing if you have a div placeholder for your table eg
function oefenen(){
var num = prompt("Zet een cijfer neer", "0");
var num1 = parseInt(num);
var table = document.getElementById("tablebody");
for(var i= 1; i< 11; i++) {
var td = document.createElement("td"); //create TD
td.innerHTML = i + " x " + num1 + " = " + (i * num1);
var tr = document.createElement("tr");
tr.appendChild(td); //add TD to the TR
table.appendChild(tr); //add TR to the table
}
//show the placeholder
document.getElementById("placeholder").style.display = "";
}
<section id="content">
<p>Wilt u de tafels leren? Klik op de knop oefenen</p>
<button id="oefenen" name="oefenen" value="oefenen" onclick='oefenen()';>Tafel oefenen! </button>
<div id="1"> <!-- I'm not sure what you use this div for -->
</div>
<div id="placeholder" style="display:none;"> <!-- Placeholder area -->
<table border="1" id="tablebody"></table>
<div>
</section>
Notice also how I var the i in the loop - otherwise you create a reference to i at the window-level, rather than just scoped to the function.
Also, the use of createElement may look long-winded - but when you come to creating mark-up of any complexity it is much preferred to setting innerHTML and concatenating strings etc. It is certainly easier to trace what is going on and break sections out into other functions.

Works ok here. ## EDITED after above comments about wanting it under the button
function oefenen() {
var num = prompt("Zet een cijfer neer", "0");
var num1 = parseInt(num);
for (i = 1; i < 11; i++) {
document.getElementById('results').innerHTML+=("<tr><td>" + i + " x " + num1 + " = " + i * num1 + "<br/></td></tr>");
}
}
<section id="content">
<p>Wilt u de tafels leren? Klik op de knop oefenen</p>
<button id="oefenen" name="oefenen" value="oefenen" onclick='oefenen()' ;>Tafel oefenen!</button>
<table border="1" id=
"results">
</table>
</section>

code as per your requirement to print the multiplication table for required number ....
<!doctype html>
<html>
<head>
<title>Tafel Trainer</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<section id="content">
<p>Wilt u de tafels leren? Klik op de knop oefenen</p>
<button id="oefenen" name="oefenen" value="oefenen" onclick='oefenen()' ;>Tafel oefenen!</button>
<br /> <br />
<div id="math">
</div>
</section>
<script>
function oefenen() {
var num = prompt("Zet een cijfer neer", "0");
var num1 = parseInt(num);
for (i = 1; i < 11; i++) {
document.getElementById('math').innerHTML+=(num1 + " x " + i + " = " + i * num1 + "<br/>");}
}
</script>
</body>
</html>

"If you execute the document.write() method on a loaded HTML document, all HTML elements will be overwritten" says w3schools
I think it is better to use innerHTML

Related

how to display numbers of value in HTML?

Few days ago I've written some JavaScript about getting some data from JSON and it successfully output on console.log.
Now I want to output values on a HTML document, try to do with a button which can refresh the data ( like I click it it request again and get new data).
The problem I facing now is , I need to output numbers of data on one line.
OUTPUT EXAMPLE:(Time), (URL), (views)Line 1 20200406 , www.XXX.com , 2000
Line 2 20200406 , www.YYY.com , 5000
Line 3 20200406 , www.YZZ.com , 9000
if I using
document.getElementById("p2").innerHTML = String({a,b,c}) ;
it only output var c
Will it be better if i use textarea ?
Thankyou.
var a='';
var b='';
var c='';
function clickme() {
for(var i=0; i<3 ;i++){
a=a++;
b=b++;
c=+b;
document.getElementById("p2").innerHTML = String({a,b,c}) ;
}
}
<!DOCTYPE HTML>
<HTML>
<head>
<title>Check UAT4 & UAT8 Version</title>
<link rel="stylesheet" type="text/css" href="test.css">
<script src="test.js"></script>
</head>
<body>
<div id="test">
<button type="button" onClick="clickme()">Click to Test</button>
<p id= "p1" >testing</p1>
<p id= "p2" >2222222</p2>
</div>
</body>
</HTML>
Use JSON.stringify({a,b,c}) instead of String({a,b,c})
var a=0, b=0, c=0;
function clickme() {
let htmlString ='';
for(var i=0; i<3 ;i++){
a++;
b++;
c=+b;
htmlString = htmlString + JSON.stringify({a,b,c}) + '<br>'
}
document.getElementById("p2").innerHTML =htmlString ;
}
<body>
<div id="test">
<button type="button" onClick="clickme()">Click to Test</button>
<p id= "p1" >testing</p1>
<p id= "p2" >2222222</p2>
</div>
If you want multiple nodes you have to create them and append to your div.
Do something like following to output 3 (or n) lines in div:
var a='', b='', c='';
function clickme() {
for(var i=0; i<3 ;i++){
a=a++;
b=b++;
c=+b;
var el = "p"+(i+2)
var node = document.createElement("p");
var textnode = document.createTextNode(JSON.stringify({a,b,c}));
node.appendChild(textnode);
document.getElementById("test").appendChild(node);
}
}
<body>
<div id="test">
<button type="button" onClick="clickme()">Click to Test</button>
<p id= "p1" >testing</p>
<p id= "p2" >2222222</p>
</div>

Append a text in container

I have created a container which displays the texts each time i click on a button. My code works fine but each time i click on a button the previous entry which is displayed in the container erases. I want to keep the previous entry and make the next text appear in the next line each time i click on a new button. Below is my code.Thank you
function appChangeFunction() {
holdtext.innerText = appchange.innerText;
}
function sharedChangeFunction() {
holdtext.innerText = sharedchange.innerText;
}
<div id="container">
<TEXTAREA ID="holdtext" rows="15" cols="70"></TEXTAREA><br><br>
</div>
<style>#container {width:100%; text-align:center;}</style>
<link rel="stylesheet" type="text/css" href="css.css" />
<button onclick="appChangeFunction()" style="background-color:white" >App Change</button>&nbsp
<button onclick="sharedChangeFunction()" style="background-color:white" >Shared Change</button>&nbsp
<SPAN ID="appchange" STYLE="display:none"> Text Under App Change
</SPAN>
<SPAN ID="sharedchange" STYLE="display:none"> Text Under Shared Change
</SPAN>
Just add the old text to the new using + sign :
<script>
function appChangeFunction() {
holdtext.innerText = holdtext.innerText + '\n' + appchange.innerText;
}
function sharedChangeFunction() {
holdtext.innerText = holdtext.innerText + '\n' + sharedchange.innerText;
}
</script>
Or using += sign and \n for new lines :
<script>
function appChangeFunction() {
holdtext.innerText += '\n'+appchange.innerText;
}
function sharedChangeFunction() {
holdtext.innerText += '\n'+sharedchange.innerText;
}
</script>
Hope this helps.
Replace your script tag with:
<script>
function appChangeFunction() {
holdtext.innerText += "\n"+appchange.innerText;
}
function sharedChangeFunction() {
holdtext.innerText += "\n"+sharedchange.innerText;
}
</script>
If first get the container data then it will be added the text
<html>
<body>
<div id="container">
<TEXTAREA ID="holdtext" rows="30" cols="70">
</TEXTAREA><br><br>
</div>
<style>#container {width:100%; text-align:center;}</style>
<link rel="stylesheet" type="text/css" href="css.css" />
<button onclick="appChangeFunction()" style="background-color:white" >App Change</button>&nbsp
<button onclick="sharedChangeFunction()" style="background-color:white" >Shared Change</button>&nbsp
<SPAN ID="appchange" STYLE="display:none"> Text Under App Change
</span>
<SPAN ID="sharedchange" STYLE="display:none"> Text Under Shared Change
</SPAN>
</body>
</html>
<script>
function appChangeFunction() {
var x = document.getElementById("holdtext").innerHTML;
holdtext.innerText = x + appchange.innerText;
}
function sharedChangeFunction() {
var x = document.getElementById("holdtext").innerHTML;
holdtext.innerText = x + sharedchange.innerText;
}
</script>

Taking the values of two same element

In console if I type this command:
document.querySelectorAll('div.information div.contact div ')[1]
The result I take is
<span class="information">
<call>number 1</call>
<call>number 2</call>
</span>
How can I take the innerHTML of call element? Should I use the nth child?
Result:
number 1
and after another command
number 2
Try this,
HTML
<span class="information">
<call>number 1</call>
<call>number 2</call>
</span>
JavaScript
var values = [];
var elements = document.getElementsByTagName('call');
for (var i = 0; i < elements.length; i++) {
values.push(elements[i].innerHTML);
}
/** ["number 1", "number 2"] **/
console.log(values);
Example
JSFiddle
There's no "call" element.
document.getElementsByClassName() is probably more appropriate in this case, but using an ID would be even easier.
window.onload = function() {
var information = document.getElementsByClassName('information')[0]
var calls = document.getElementsByClassName('call');
var numbers = [];
for (var i = 0; i < calls.length; i++) {
numbers.push(calls[i].innerHTML);
}
for (var i = 0; i < numbers.length; i++) {
document.getElementById('numbers').value += numbers[i] + '\n';
}
}
<span class="information">
<span class="call">number 1</span>
<span class="call">number 2</span>
</span>
<h2>Added so we can see something without looking at the console:</h2>
<form name="form" id="form">
<textarea id="numbers"></textarea>
</form>
<html>
<head>
<title>
Practice
</title>
</head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var data = document.getElementsByTagName("call");
for(var i=0;i<data.length;++i)
{
var scope = $(data[i]).html();
console.log(scope);
}
});
</script>
<body>
<span class="information">
<call>number 1</call>
<call>number 2</call>
</span>
</body>

Datatables updating only rows without reloading table

BACKGROUND:
I have a small jquery app that contains widgets. There are 2 types of widgets in this app and they are counter widgets and grid widgets. For grid widgets i am utilizing dataTables.
My app basically connects to a server and recieves various information such as widget names etc. So based on the information received i dynamically create pages for each widget. Things are working fine at the moment but i am facing a little problem.
Problem
The issue i have right now is to do with my grid widgets which utilize dataTables api.From my server I receive the grid information in this format.
//EXAMPLE INPUT
/*
<?xml version="1.0" encoding="UTF-8"?>
<rows>
<head>
<column width="55" type="ro" align="left" sort="str">Player</column>
<column width="55" type="ro" align="left" sort="str">State</column>
<column width="55" type="ro" align="left" sort="str">Points</column>
</head>
<row id="1">
<cell>Lebron King James</cell>
<cell>Best Mode</cell>
<cell>45</cell>
</row>
</rows>
*/
Then i parse it to the appropriate table format (function createTableStringFromXML) so it works with the datatables.
My table is reloading every 3 seconds. So this is the problem.
Eventhough i want my table to update i think reloading the entire table is bad because not only does it look weird but i think it is not necessary. I was wondering is there way i can write some function that compares the old table with the new updated table and only updates rows that need update? So this way the entire table it self is not loaded?
MY HTML CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>NBA Fanatico</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="themes/tdMobile.min.css" />
<link rel="stylesheet" href="themes/jquery.mobile.icons.min.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0/jquery.mobile.structure-1.4.0.min.css" />
<link rel="stylesheet" type="text/css" href="cssfinal/style.css" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js"></script>
<script src="dhtmxSuite/dhtmlxWindows/codebase/dhtmlxcommon.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
<script src="jquery.ui.touch-punch.min.js"></script>
<!-- MAIN JS SCRIPT CONTANS CODE FOR COUTNER WIDGETS, TABLES , AJAX REQUEST FOR GETTING DATA-->
<script src="dynamic.js"></script>
<!-- SCRIPTS FOR DATA TABLES -->
<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css" />
<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
</head>
<body>
<!-- PAGE 1 -->
<div data-role="page" data-theme="a" id="page1">
<!-- <div data-role="header" data-position="fixed">
<h1></h1>
</div> -->
<div data-role="content" data-theme="a">
<div class="login-box" id="login">
<div id="loginprompt">
<div id="header">
<h3>Basketball Fanatico</h3>
</div>
</div>
<form method="GET">
<div id="username" data-role="fieldcontain">
<input type="text" name="username" placeholder="Username" />
</div>
<div id="password" data-role="fieldcontain">
<input type="password" name="password" id="txtId" placeholder="Password"/>
</div>
<div id ="loginbtn">
<a data-role="button" id="log" data-theme="a" href="#page2" data-transition="slide">LOGIN</a>
</div>
</form>
<br />
</div>
</div>
</div>
</div>
<!-- PAGE 2 -->
<div data-role="page" id="page2">
<div data-role ="header" data-position="fixed" data-theme="a">
<a data-iconpos="notext" href="#panel" data-role="button" data-icon="bars"></a>
<h1 class="ui-title" role="heading">Basketball Fanatico</h1>
<div class="ui-btn-right" data-type="horizontal">
<a data-iconpos="notext" href="#page2" data-role="button" data-icon="home" ></a>
<a data-iconpos="notext" href="#page1" data-role="button" data-icon="delete" ></a>
</div>
</div>
<div data-role="content" id="page2content">
<ul data-role="listview" data-inset="true">
<li data-role="list-divider" data-theme="a">WELCOME!</li>
<li>Use the menu on the left to navigate <br />and configure the various options.</li>
</ul>
</div>
</div>
<div data-role="panel" id="panel" data-position="left" data-theme="a" data-display="push">
<!-- <div> -->
<div id="nav"><h3>Navigation</h3>
<hr>
<label>
<input id="chkSort" type="checkbox" checked="true" />Allow sorting</input>
</label>
<hr>
</div>
<div id="items" data-role="button">
<!-- Insert Parsed Widget Names Here -->
LOG OUT
</div>
<!-- </div> -->
</div>
</body>
</html>
MY JS
var widgetNames = new Array();
var widgetId = new Array();
var pageId = ''
$( document ).on( "pagecreate", function() {
$( "body > [data-role='panel']" ).panel().enhanceWithin();
//Format the grid as required
$('#example2').dataTable( {
"bPaginate": false,
"bFilter": true,
"bAutoWidth": false,
"oLanguage": { "sSearch": "" }
} );
$('.dataTables_filter input').attr("placeholder", "Search");
$('.dataTables_filter').css('float','none');
$('.dataTables_filter').css('padding-right','0px');
$("#example_filter").detach().prependTo('#header1');
});
$(document).on('pagecreate', '#page1', function() {
// $( ":mobile-pagecontainer" ).on( "pagecontainershow", function( event, ui ) {
// pageId = $('body').pagecontainer('getActivePage').prop("id");
// alert( "The page id of this page is: " + pageId );
// });
$("#log").on('click', function(){
$.ajax({
url: "script.login",
type: "GET",
data: { 'page':'create_user', 'access':'user','username':$("input[name='username']").val(), 'password':$("input[name='password']").val()},
dataType: "text",
success: function (html) {
//console.log(html);
widgetNames = new Array();
widgetId = new Array();
var res = html.match(/insertNewChild(.*);/g);
//Get each widget name and ID and assign to values in an array
for(var i =0;i<res.length;i++){
//alert(res[i]);
var temp = res[i].split(',');
if(temp.length >= 3){
widgetNames[i] = (temp[2].replace('");','')).replace('"','');
widgetId[i] = temp[1].replace("'","").replace("'","").replace(/ /g,'');
}
}
var AllWidgets = ''
var testwidget = new Array();
//Loop through the html returned and get the data relevant to each widget... save in temp array
var tempWidgetContent = html.match(/w\d+\.isHidden(.*)\(\) == false\)[\s\S]*?catch\(err\)\{ \}/gm);
for(var i =0;i<tempWidgetContent.length;i++){
var widgetContent = tempWidgetContent[i].substring(tempWidgetContent[i].indexOf('{')+1);
//alert(widgetContent);
//This alone handles coutners...
testwidget[i] = widgetContent.replace("site +","");
//replace the code for a grids...
if(testwidget[i].indexOf('grid') > 0){
testwidget[i] = CreateGridUpdateFunction(testwidget[i],i);
}
}
var widgetPart = new Array();
//Assume we have widget names, ids, and loading data in 3 arrays
//Loop through and create the necessary page.
for(var i = 0; i<widgetNames.length; i++){
if(testwidget[i].indexOf('hi') > -1){
// alert('WORKING');
var pageHeaderPart = "<div data-role= 'page' id='"+widgetId[i]+"' data-pageindex='"+i+"' class='dynPageClass'><div data-role='header' id='header1' data-position='fixed' data-theme='a'><a href='#panel' data-icon='bars' data-iconpos='notext' class='ui-btn-left'></a><a href='#' data-icon='search' id='search' data-iconpos='notext' class='ui-btn-left' style='margin-left: 35px'></a><h1>BASKETBALL FANATICO</h1><a href='#page1' data-icon='delete' data-iconpos='notext' class='ui-btn-right'></a><a href='#page2' data-icon='home' data-iconpos='notext' class='ui-btn-right' style='margin-right: 35px;'></a></div><div data-role='content'>";
}
else{
var pageHeaderPart = "<div data-role='page' id='"+widgetId[i]+"' data-pageindex='"+i+"' class='dynPageClass'><div data-role='header'data-position='fixed' data-theme='a'><a data-iconpos='notext' href='#panel' data-role='button'data-icon='bars'></a><h1 class='ui-title'role='heading'>BASKETBALL FANATICO</h1><div class='ui-btn-right' data-type='horizontal'><a data-iconpos='notext' href='#page2' data-role='button'data-icon='home'style=\" margin-right:5px; \"></a><a data-iconpos='notext' href='#page1' data-role='button'data-icon='delete'></a></div></div><div data-role='content'>";
}
var pageFooterPart = "</div><div data-role='footer' data-position='fixed'><span class='ui-title'><div id='navigator'></div></span></div></div>";
if(testwidget[i].indexOf('hi') > -1){
// alert('i am a grid');
var check = "<div data-role='tbcontent'><ul data-role='listview'data-insert='true'><li data-role='list-divider' data-theme='a'>"+widgetNames[i]+"";
}
var check = "<div data-role='content'><ul data-role='listview'data-insert='true'><li data-role='list-divider' data-theme='a'>"+widgetNames[i]+"</div>";
if(testwidget[i].indexOf('counterValue') > 0){
// alert('i am a counter');
widgetPart[i] = '<DIV style=\" text-align: center; background-color:#EDEDED; padding-bottom: auto; font-size: 55pt;\" id=widgetContainer_'+widgetId[i]+'></DIV><SCRIPT>' + 'function UpdateWidgetDiv'+widgetId[i]+'() {' + testwidget[i] + '$(\"#widgetContainer_'+widgetId[i]+'").html(counterValue);' + '}' + '</SCRIPT>';
}
if(testwidget[i].indexOf('hi') > -1){
// alert('i am a grid');
widgetPart[i] = '<DIV id=widgetContainer_'+widgetId[i]+'></DIV><SCRIPT>' + 'function UpdateWidgetDiv'+widgetId[i]+'() {' + testwidget[i] + '}' + '</SCRIPT>';
}
else {
widgetPart[i] = '<DIV style=\" text-align: center; background-color:#EDEDED; padding-bottom: auto; font-size: 55pt;\" id=widgetContainer_'+widgetId[i]+'>I dont know what I am</DIV>';
}
AllWidgets +='<a href="#'+widgetId[i]+'" class="widgetLink" data-theme="b" data-role="button" >'+widgetNames[i]+'</a>';
var makePage = $(pageHeaderPart + check + widgetPart[i] + pageFooterPart);
makePage.appendTo($.mobile.pageContainer);
}
$('#items').prepend(AllWidgets).trigger('create');
//Widget Update Function
function UpdateActivePage(){
//get active page
pageId = $(":mobile-pagecontainer" ).pagecontainer('getActivePage').prop("id");
//figure out index
var idx;
for (var i=0; i<widgetId.length; i++){
if (widgetId[i] == pageId){
idx = i;
break;
}
}
//alert(pageId);
//run your update
//alert("RUNNING:");
eval(testwidget[idx]);
//alert('Updateing active page');
$("#widgetContainer_" + pageId).html(counterValue);
$('#grid_'+idx).dataTable( {
"bPaginate": false,
"bFilter": true,
"bAutoWidth": false,
"oLanguage": { "sSearch": "" }
} );
$('.dataTables_filter input').attr("placeholder", "Search");
$('.dataTables_filter').css('float','none');
$('.dataTables_filter').css('padding-right','0px');
$("#example_filter").detach().prependTo('#header1');
}
function CreateGridUpdateFunction(oldUpdatefunction,thisWidgetID)
{
var updateLines = oldUpdatefunction.split("\n");
var updateFunctionCode = "";
for (var i=0; i<updateLines.length;i++)
{
if(updateLines[i].indexOf(" var url = ") > 0)
{
var updateURL = updateLines[i];
if(updateURL.indexOf("&windowWidth=") > 0){
updateURL = updateURL.substr(0,updateURL.lastIndexOf("&windowWidth=")) + "';";
}
updateFunctionCode += updateURL;
updateFunctionCode += " var loader = dhtmlxAjax.getSync(url);";
updateFunctionCode += " if(loader.xmlDoc.responseText.length > 0){";
updateFunctionCode += " counterValue = createTableStringFromXML(loader.xmlDoc.responseText,"+thisWidgetID+");";
updateFunctionCode += " } ";
}
}
return "var counterValue = \"hi\"; "+updateFunctionCode ;
}
$(":mobile-pagecontainer" ).on( "pagechange", function() { UpdateActivePage(); } )
setInterval(UpdateActivePage, 3000);
}
});
});
});
//Returns a bool indicated if the (space trimmed) string starts with needle.
function startsWith(searchString,searchVal){
var search = searchString.trim();
return search.indexOf(searchVal) >= 0;
}
function createTableStringFromXML(serverXML,thisWidgetID){
console.log(serverXML);
var xmlLines = serverXML.split("\n");
var returnTable = "";
for (var i=0; i<xmlLines.length;i++)
{
if(startsWith(xmlLines[i],"<rows"))
{
returnTable += "<table cellpadding=\"2\" cellspacing=\"2\" border=\"0\" class=\"display\" id=\"grid_"+thisWidgetID+"\" width=\"100%\">";
}
else if(startsWith(xmlLines[i],"</rows>"))
{
returnTable += "</tbody></table>";
}
else if(startsWith(xmlLines[i],"<head>"))
{
returnTable += "<thead><tr>";
}
else if(startsWith(xmlLines[i],"</head>"))
{
returnTable += "</tr></thead><tbody>";
}
else if(startsWith(xmlLines[i],"<column"))
{
returnTable += "<th>"+xmlLines[i].match(/>(.*?)</i)[1]+"</th>";
}
else if(startsWith(xmlLines[i],"<row"))
{
returnTable += "<tr>";
}
else if(startsWith(xmlLines[i],"</row"))
{
returnTable += "</tr>";
}
else if(startsWith(xmlLines[i],"<cell"))
{
returnTable += "<td>"+xmlLines[i].match(/>(.*?)</i)[1]+"</td>";
}
console.log(returnTable);
}
return returnTable ;
}
Please advice on how to achieve this. I am sorry if you have not understood my question so please ask me again. I am only using HTML and JS for couple of months so i am band new to this and that also might be the reason why my question might sound silly to some of you so sorry in advance. I apologize for my poor english please let me know if you dont understand. Thanks.
Updating the table every 3 seconds could cause performance issues, especially if you have lots of rows!
If you want to do it, you can iterate through the rows in the update XML and then write the values to the individual cells in the table.
DEMO
In my example, the table is already there with row ids as data attributes on the row element. I am updating once on a button click instead of every 3 seconds on a timer, but the parsing would be the same.
$("#update").on("click", function(){
var $trows= $('#example tbody tr');
var xmlDoc = $.parseXML( xmlstring );
var $xml = $( xmlDoc );
$xml.find("row").each(function(index){
var id = $(this).prop("id");
var $cells = $(this).find("cell");
var c1 = $cells.eq(0).text();
var c2 = $cells.eq(1).text();
var c3 = $cells.eq(2).text();
//get row in table with this id
var $rowtd = $('#example tbody [data-id=' + id + '] td');
$rowtd.eq(0).text(c1);
$rowtd.eq(1).text(c2);
$rowtd.eq(2).text(c3);
});
});
The code loads the XML string into an XmlDocument and then creates a jQuery object from the document. Next I iterate through all the Xml Nodes called "row" getting the id and the 3 cell texts. Then I find the row in the existing table with the same Id and write the texts into the existind TDs in the row.
You will need to test the performance of this given the normal number of rows you have and the types of devices you plan to support.

onmouseover for pictures in Firefox and Chrome

I have problems with mouseover in Mozilla and Chrome after making it work in IE, for sure I can tell you that my code worked perfectly in Chrome at least, because that's my default browser and I used it for debugging when creating the Javascript and it worked nicely... until I tried to make it work in IE too.
Here I post the full code of the webpage I'm having trouble with:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebbShop.aspx.cs" Inherits="FSwebportal.WebbShop" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<style>
.prodShow{width: 100%; text-align:center;border:0; float:right; position:inherit; padding-left:310px;}
#prodFollow{display:block; width:100%; height:100%; position:fixed; overflow:hidden;}
#orderSett{display:block; position:relative; float:left; padding-top:inherit;}
.ShowBig{width:290px;height:290px; padding-top:10px;}
.pTb{width:50px;}
.order{background-color:Transparent;margin:3px;}
.txtArea{border:0;overflow:auto;width:200px;height:100px;}
.prodRow{background-image:url("produktbakgrund.png"); background-repeat:repeat;}
.row{background-color:Transparent;width:100%;margin: 0px auto;display:inline-table;}
.col{background-color:Transparent;width:100%;margin:3px;}
</style>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<center><input type="button" value="Visa allt" onclick="javascript:appendRow()" class="append_row" /></center>
<hr />
<div id="prodFollow">
<table id="dumbTable">
<tr>
<td>
<img id="sideImg" class="ShowBig" src="" alt=""/>
</td>
</tr>
<tr>
<td>
<h3><b>Specifikationer:</b></h3>
<select name="">
</select>
</td>
</tr>
</table>
</div>
<table id="itemList" class="prodShow" cellspacing="0">
<thead>
<tr class="prodRow">
<th>Bild</th>
<th>Förklaring</th>
<th>Artikelnummer</th>
<th>Pris</th>
</tr>
</thead>
</table>
<script type="text/javascript">
function appendRow() {
var tbl = document.getElementById('itemList');
var len = <%= aspInfo.Count %>;
var arr = new Array(len);
var currIndex = 0;
var imgID=0;
<%
for (int x = 0; x < aspInfo.Count; x++) {
Response.Write("arr["+x+"]= '"+ aspInfo[x]+"';");
}
%>
for(row =0; row < arr.length/4;row++)
{
var rad = tbl.insertRow(tbl.rows.length);
rad.setAttribute('class','prodRow');
for (c = 0; c < tbl.rows[row].cells.length; c++)
{
if(c < 1)
{
createCell(rad.insertCell(c), arr[currIndex], 'col',imgID);
imgID++;
}
else {
if(c < 3)
{
createCell(rad.insertCell(c),"<Label class=txtArea>" + arr[currIndex] + "</Label>", 'row',imgID);
}
else
{
createCell(rad.insertCell(c),"<Label class=txtArea>" + arr[currIndex] + " SKR</Label><br>Antal:<input type=text class=pTb /><input type=button width=100px value='Lägg i varukorg'></input>", 'order',imgID);
}
}
currIndex++;
}
}
}
function createCell(cell, text, style,imgID) {
if (style == 'col') {
var arrLen = <% = largeImg.Count %>;
var imgArr = new Array(arrLen);
<%
for (int x = 0; x < largeImg.Count; x++) {
Response.Write("imgArr["+x+"]= '"+ largeImg[x]+"';");
}
%>
var div = document.createElement('div');
div.setAttribute('class', style);
div.setAttribute('className', style);
div.innerHTML = "<a href='#'><img id='" + imgID + "' src='" + text + "' onmouseover=javascript:onImg('" + imgArr[imgID] + "') border='0' alt='Animg' /></a>";
cell.appendChild(div);
}
else {
var div = document.createElement('div');
div.setAttribute('class', style);
div.setAttribute('className', style);
div.innerHTML = text;
cell.appendChild(div);
}
}
</script>
<script type="text/javascript" language="javascript">
function onImg(bigImg) {
var img = document.getElementById('sideImg#');
img.src = bigImg;
alert(img.src.toString());
}
</script>
</form>
</body>
</html>
I hope you can solve it for me.
// wrong var img = document.getElementById('sideImg#');
var img = document.getElementById('#sideImg');
Hope this helps
Thanks for your reply John.
I've figured out the problem, and it was not the code that was wrong.
It was my own fault, created a div to contain a picuture on the left hand side.
Problem was that the div did not think the left hand side was enough but covered full width of the page there by hideing the pictures behind it:P
Well hope this helps someone else doing the same mistake in the future.
regards David

Categories