I used HTML and JAVAscript in one page.
But when i enter the site, and see.
I can see only JAVAscript, not HTML source.
There are few line of HTML string, and one jaascript which creat table
In the page, i can see only table, not few of HTML string
In the body code below,
Only i can see "script ~~/script" Only!
I can't see this below in the web page.
<br>
Back to admin main page <br>
Go to food list <br>
Go to food detail list <br>
This is the body code
<body>
<br>
Back to admin main page <br>
Go to food list <br>
Go to food detail list <br>
<script>showFoodList();</script>
</body>
this is a whole code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script language="javascript">
// this function is used to ask food to server and take a data with json
function showFoodList(){
var para = document.location.search;
fetch("http://gyrjs07.dothome.co.kr/what_to_eat/foodlist.php")
.then(function(response) {
return response.json();
})
.then(function(myJson) {
creatTable(myJson);
});
}
function creatTable(data){
document.write("<table width='80%' border='1' style='margin: auto; text-align: center'>");
// for문 시작
for ( var i=0; i<data.length ; i++) {
document.write("<tr>"); // <tr> : 행추가
// 이중 for문 시작
for ( var j=0; j<data[i].length ; j++) {
var txt=data[i][j]; // 테이블각 셀에값을 출력
document.write("<td>"+ txt +"</td>"); // <td> : 열추가.
}
document.write("</tr>");
} //end for i
document.write("</table>"); // 테이블 태그를 닫는다.
}
</script>
</head>
<body>
<br>
Back to admin main page <br>
Go to food list <br>
Go to food detail list <br>
<script>showFoodList()</script>;
</body>
</html>
It happens because you use document.write method. It automatically calls document.open which removes all existing nodes in a document.
Documentation for Document.write() and Document.open()
Better approach is append children to some predefined node as it shown in snippet below.
const fakeApiResponse = [
["number", "name", "q-ty"],
["1.", "soda", "2"],
["2.", "beer", "3"],
["3", "pizza", "3"]
];
// this function is used to ask food to server and take a data with json
function showFoodList() {
// Emulate api call to get data
Promise.resolve(fakeApiResponse).then(function(myJson) {
creatTable(myJson);
});
}
function creatTable(data) {
// Get mountig node from HTML
const mountingPoind = document.getElementById("food-list");
// Create Table element and set some attributes
const table = document.createElement("table");
table.setAttribute("width", "80%");
table.setAttribute("border", "1");
table.setAttribute("style", "margin: auto; text-align: center");
// Start iterate over data to create table structure
for (let i = 0; i < data.length; i++) {
createTableRow(table, data[i]);
}
// Append table structure to mounting point
mountingPoind.appendChild(table);
}
// Creates row. Add text call createCell function to generate cells with data
// and append it to parent
function createTableRow(parent, rowData) {
const row = document.createElement("tr");
for (let j = 0; j < rowData.length; j++) {
createCell(row, rowData[j]);
}
parent.appendChild(row);
}
// Creates cell. Add text data to it and append it to parent
function createCell(parent, cellData) {
const cell = document.createElement("td");
cell.innerText = cellData;
parent.appendChild(cell);
}
showFoodList();
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<br />
Back to admin main page <br />
Go to food list <br />
Go to food detail list <br />
<br />
<div id="food-list"></div>
<script src="src/index.js"></script>
</body>
</html>
Related
I have a table generated from a textarea filled by users, but some of the time, a cell stays empty (and that's all right).
The thing is that the .innerHTML of that cell is also my var y in a script and when that cell is empty (therefore, undefined), my var y becomes UNDEFINED too (the value, not a string), which makes my whole script fail.
Here's a snippet to show the problem:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body><center>
</center></body>
<!--------- script that generates my table from text areas -->
<script>
function generateTable() {
$('#excel_table1').html("");
var n=1;
var rows=[];
var lng=0;
var maxligne=0;
$('textarea').each(function(){
var data = $(this).val();
if (data !=''){
var rowData = data.split("\n");
rows[n] = rowData;
lng = rowData.length;
if(lng > maxligne)
{
maxligne=lng
}
n++;
}
}
)
var table = $('<table />');
k=0;
while (k < maxligne) {
var row = $('<tr />');
for(var i = 1; i < rows.length; i++)
{
var singleRow = rows[i];
if(singleRow[k]!= undefined){
row.append('<td>'+singleRow[k]+'</td>')
} else {
row.append('<td></td>')
}
}
table.append(row);
k++;
}
$('#excel_table1').append(table);
}
</script>
<textarea placeholder="data 2 Here" name="data1" style="width:100px;height:40px;"></textarea>
<textarea placeholder="data 2 Here" name="data2" style="width:200px;height:40px;"></textarea>
<textarea placeholder="fild not required" name="data3" style="width:200px;height:40px;"></textarea>
<br>
<input id=bouton1 type="button" onclick="javascript:generateTable()" value="GenerateTable"/>
<div id="excel_table1"></div>
<!--------- script that get the data from cells to show it in <H2> -->
<script type="text/javascript">
function buttonTEST()
{
$('#displayCell').html("");
var x = document.getElementById('excel_table1').getElementsByTagName('tr')[0].cells[1].innerHTML;
var y = document.getElementById('excel_table1').getElementsByTagName('tr')[0].cells[2].innerHTML;
if (y === undefined) {
y = " ";
}
document.getElementById('displayCell').innerHTML = x +" "+ y;
}
</script>
<br/><br/>
<h2 id="displayCell"></h2>
<br/><br/>
<input id="Button2" type="button" onclick="buttonTEST()" value="TEST ME"/>
As you can see, if you generate a table with only to columns (which is supposed/needs to happen sometimes), we get this error from the console because we're trying to get "innerHTML" from a undefined:
index.html:120 Uncaught TypeError: Cannot read property 'innerHTML' of undefined
A little specification: When that cell is=undefined , I need it to stay undefined, I only want to change the fact that my var y also becomes undefined.
So I thought that changing the value of var y (and not the value of that cell, otherwise, the 3rd column, supposed to be empty, would be created just because of an blank space) to a blank space would resolve the problem, but I don't seem to get it right (write it in a correct manner).
Any ideas?
Try
var x = document.getElementById('excel_table1').rows[0].cells[0].innerHTML;
var y = document.getElementById('excel_table1').rows[0].cells[1].innerHTML;
using rows instead of getElementsByTagName is cleaner.
Also note that the indexes for cells start from zero not 1, you probably only have 2 cells in your first row, but .cells[2].innerHTML tries to get the innerHTML of the 3rd cell which does not exist.
As others have pointed out, you're already using jQuery, so the easiest way to get the cell contents is to use a css selector to find the cells using the $ function, then call .html() to get the contents. A direct conversion of your current code to this approach could be:
var x = $('#excel_table1 tr:nth-child(1) td:nth-child(2)').html();
var y = $('#excel_table1 tr:nth-child(1) td:nth-child(3)').html();
This works in a way so that the $ function returns a jQuery object, which is essentially a set of elements, which can potentially be empty. Most jQuery functions are then designed to fail gracefully when called on an empty set. For instance, html will return undefined when invoked on an empty set, but it will not fail.
Note that it is not very robust to use the selector above, as it is obviously sensitive to the placement of the cells. It would be more maintainable to assign a class attribute to the cells that describes their content, and then select on that, e.g. something like
var name = $("#excel_table1 tr:nth-child(1) td.name").html()
So here's the answer that worked for me:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body><center>
</center></body>
<!--------- script that generates my table from text areas -->
<script>
function generateTable() {
$('#excel_table1').html("");
var n=1;
var rows=[];
var lng=0;
var maxligne=0;
$('textarea').each(function(){
var data = $(this).val();
if (data !=''){
var rowData = data.split("\n");
rows[n] = rowData;
lng = rowData.length;
if(lng > maxligne)
{
maxligne=lng
}
n++;
}
}
)
var table = $('<table />');
k=0;
while (k < maxligne) {
var row = $('<tr />');
for(var i = 1; i < rows.length; i++)
{
var singleRow = rows[i];
if(singleRow[k]!= undefined){
row.append('<td>'+singleRow[k]+'</td>')
} else {
row.append('<td></td>')
}
}
table.append(row);
k++;
}
$('#excel_table1').append(table);
}
</script>
<textarea placeholder="data 2 Here" name="data1" style="width:100px;height:40px;"></textarea>
<textarea placeholder="data 2 Here" name="data2" style="width:200px;height:40px;"></textarea>
<textarea placeholder="fild not required" name="data3" style="width:200px;height:40px;"></textarea>
<br>
<input id=bouton1 type="button" onclick="javascript:generateTable()" value="GenerateTable"/>
<div id="excel_table1"></div>
<!--------- script that get the data from cells to show it in <H2> -->
<script type="text/javascript">
function buttonTEST()
{
$('#displayCell').html("");
var x = $('#excel_table1 tr:nth-child(1) td:nth-child(2)').html();
var y = $('#excel_table1 tr:nth-child(1) td:nth-child(3)').html();
if (y ===undefined)
{document.getElementById('displayCell').innerHTML = x ;}
else
{document.getElementById('displayCell').innerHTML = x +" "+ y;}
}
</script>
<br/><br/>
<h2 id="displayCell"></h2>
<br/><br/>
<input id="Button2" type="button" onclick="buttonTEST()" value="TEST ME"/>
I'm trying to ask the user through a prompt for a number that is an: integer, greater than 0, and is numeric. I did that with a do while loop and seems to be working correctly. With that number I have to pass it to the function called "genTable" and create a table with a dynamic amount of rows based on what the user typed. However, with my current code I can't seem to get the table to appear on the page. Any ideas on where I went wrong and how to fix it?
<!DOCTYPE HTML>
<html>
<head>
<title>jsLoopDemo</title>
<!--
Honor Code: I acknowledge that this code represents my own work: CC
Date: July 6, 2017
-->
<meta charset="utf-8" />
<meta name="description" content="Create a chart with rows based on a number
user chose." />
<meta name="keywords" content="loop, row, dynamic" />
<meta name="author" content="" />
<script type="text/javascript">
do{
var numChose = prompt("Please enter an interger greater than zero.");
}while (isNaN(numChose) || numChose % 1 !== 0 || numChose < 1 );
function genTable(numChose)
{
var table = document.createElement("TABLE");
var tableBody = document.createElement("TBODY");
table.appendChild(tableBody);
var myTableDiv = document.getElementById("mytable");
for (var r = 0; r <= numChose; r++)
{
var tr = document.createElement("TR");
tableBody.appendChild(tr);
var td = document.createElement("TD");
tr.appendChild(td);
td.appendChild(document.createTextNode("Row " + r));
}
myTableDiv.appendChild(table);
}
</script>
</head>
<body>
<div id="mytable">
</div>
</body>
</html>
Two things:
You need to actually call the function after the prompt, so you need to add a line after your do while:
genTable(numChose);
That still won't work, since the DOM will not be ready (myTableDiv will be undefined), so you need to wrap your entire code in an event listener:
document.addEventListener("DOMContentLoaded", function(event) {
//do work
});
Move the <script> code after the
<div id="mytable">
</div>
in <body> so that the element is rendered on DOM while table is being generated and call the function
genTable(numChose);
after you get the number from user.
How would you start writing a for loop for the code provided below:
<html>
<head>
</head>
<body>
Rows: <input name="rows" id="rows" type="text"/><br/>
<input type="submit" value="Make me a table!" onclick="makeTable();"/><br/><br/>
<table border="1" id="theTable">
</table>
<script type="text/javascript">
function makeTable(){
//Insert code here AND ONLY HERE!
//Write a for loop to create the number of rows specified in the "row" input field
</script>
</body>
</html>
As I suspect this is homework I will no provider a full code answer but instead provide you with a few guide lines that hopefully will help you.
You have the html and the javascript, in order to create new html elements you need to use the document.createElement(type) function that will create a new element, in your case - td/th ?
Then you need to insert it into your table
You do that by obtaining the table(by id/type) - search the web for this one its very simple.
And then using the append method on is with the created element.
You do all this process with a normal for loop that will run until the .value of the input tags you have in your html (Again, search for how to obtain these values)
Good luck =]
Is this what you are looking for?
function makeTable(){
// Get values of rows/cols inputs
var rows = document.getElementById('rows').value;
var cols = document.getElementById('cols').value;
// Check the values are in fact numbers
if (!isNaN(rows) && !isNaN(cols)) {
// Get the table element
var table = document.getElementById('theTable');
// Iterate through rows
for (var r = 0; r < rows; ++r) {
// Create row element
var tr = document.createElement('tr');
// Iterate through columns
for (var c = 0; c < cols; ++c) {
// Create cell element
var td = document.createElement('td');
// Setting some text content
td.textContent = 'R: ' + r + ', C: ' + c;
// Append cell to row
tr.appendChild(td);
}
// Append row to table
table.appendChild(tr);
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
Rows: <input name="rows" id="rows" type="text"/><br/>
Cols: <input name="cols" id="cols" type="text"/><br/>
<input type="submit" value="Make me a table!" onclick="makeTable();"/> <br/><br/>
<table border="1" id="theTable">
<script type="text/javascript">
function makeTable(){
var html = "";
var row=$('#rows').val();
var col=$('#cols').val();
for(var i=0; i<row; i++){
html+="<tr>";
for(var j=0;j<col; j++)
{
html+= '<td> Your data </td>';
}
html+="</tr>"
}
$('#theTable').html(html);
//Insert code here AND ONLY HERE!
//Write a for loop to create the number of rows specified in the "row" input field
//create a dom element for the row to be added to the table
}
</script>
</body>
</html>
I have kept it simple. Hope it helps.
i have a code that is supposed to read from a html file, split it into an array and display parts of that array, but when going though with alert, i found that $.get is not actually getting the file
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
</head>
<body>
<button onclick="myfunction()">update</button>
<div id="div1"></div>
<script>
function myfunction() {
var info = "";
$.get("../Read_Test/text.html", function(data) {
SomeFunction(data);
});
alert(info);
var array = info.split("§n");
var people = array[1].split(",");
for (var i = 0; i < people.length; i++) {
document.getElementById("div1").innerHTML = people[i] + "<br>";
}
}
function SomeFunction(data) {
var info = data;
}
</script>
</body>
</html>
the directories are on a server and go like so:
Sublinks->Read_Test->This_File.html,text.html
The objective of this is that a file would have something along the lines of "a§nb1,b2,b3,§n" and the script would split it via "§n" then get "array[1]" and split that via ",". lastly it displays each part of that newly created array on a new line, so a file with "a§nb1,b2,b3,§n" would result in:
b1
b2
b3
Please help
Ajax is asynchronous, it make request and immediately call the next instruction and not wait for the response from the ajax request. so you will need to process inside of $.get. success event.
I have changed delimiter character to ¥. change same in text.html. problem was you have not mentioned character set to utf8 and due to this it could not recognized the special character and subsequently not able to split the string. i have aldo document type to HTML5.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myfunction()">update</button>
<div id="div1"></div>
<script>
function myfunction() {
$.get("../Read_Test/text.html", function(data) {
var info = data;
var array = info.split("¥");
var people = array[1].split(",");
for (var i = 0; i < people.length; i++) {
document.getElementById("div1").innerHTML += people[i] + "<br>";
}
});
}
</script>
</body>
</html>
I am trying to create an array that pass one item waits for a response from my node server from a list.
My data input to JavaScript is from a text area in html then I am trying to send each line one at a time it can only send the next array item when my nodeJS has finished can anyone show me any example's or ways to post an array one item at a time.
instead of in one big chunk like I am getting currently.
<script src="js/socket.io.js"></script>
<script type="text/javascript">
function textareaToArray(t){
return t.value.split(/[\n\r]+/);
}
function showArray(msg){
for(i = 0; i < msg.length; i++) {
// something per item
socket.emit("dout", { message : msg[i] } );
}
// the old code
// document.getElementById("message").innerHTML = msg.join("
");
}
</script>
<script>
var socket = io.connect("https://json2-c9-ashg1990.c9.io");
socket.on("news", function(data) {
document.getElementById("message").innerHTML = JSON.stringify(data.hello);
});
// socket.emit("my other event", { message : "client emit" } );
</script>
my full html
<html>
<html>
<head>
<title>Welcome To ....</title>
<script src="js/socket.io.js"></script>
<script type="text/javascript">
function textareaToArray(t){
return t.value.split(/[\n\r]+/);
}
function showArray(msg){
for(i = 0; i < msg.length; i++) {
// something per item
socket.emit("dout", { message : msg[i] } );
}
// the old code
// document.getElementById("message").innerHTML = msg.join("
");
}
</script>
<script>
var socket = io.connect("https://json2-c9-ashg1990.c9.io");
socket.on("news", function(data) {
document.getElementById("message").innerHTML = JSON.stringify(data.hello);
});
// socket.emit("my other event", { message : "client emit" } );
</script>
</head>
<body>
<h1> WELCOME TO .... </h1>
<form>
<textarea rows="10" cols="60" name="alpha"></textarea>
<br>
<input type="button" value="show array" onclick="showArray(textareaToArray(this.form.alpha ))">
</form>
<br>
<textarea id="message" rows="6" cols="60" name="message"></textarea>
</body>
</html>
Well, you code seems OK, except the regexp you use.
You should split the string using \n character. You are using \n\r, which is not a Windown line break character sequence.
Window character sequence is \r\n.
See here: http://www.regular-expressions.info/nonprint.html