Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to fill my HTML table with my array. I tried it with $rowTemplate.find('[data-id=id]').text(id);
But it didn't work. I work with sockets so I can't post all of my code that would be too confusing.
I will ads some of my code but it's a general question how to fill a HTML table with input of an two dim array.
socket.on('outputData', function(data) {
var $rowTemplate = $('<tr><td data-id="id"></td><td data-id="name"></td><td data-id="geburtsort"></td><td data-id="geburtsdatum"></td><td data-id="favorite"></td></tr>');
var resultArray = data.resultArray;
var name, location, bdate, id, anzahl = 0;
for (var i = 0; i < resultArray.length; i++) {
name = resultArray[i][0];
anzahl = anzahl + 1;
console.log(name);
location = resultArray[i][1];
bdate = resultArray[i][2];
favorit = resultArray[i][3];
id = resultArray[i][4];
$rowTemplate.find('[data-id=id]').text(id);
$rowTemplate.find('[data-id=name]').text(name);
$rowTemplate.find('[data-id=geburtsort]').text(location);
$rowTemplate.find('[data-id=geburtsdatum]').text(bdate);
}
$("#table > tbody").append(rowTemplate.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<table id="table">
<tbody>
<tr>
<th>ID</th>
<th>Name</th>
<th>Geburtsort</th>
<th>Geburtsdatum</th>
<th>Favorit</th>
</tr>
</tbody>
</table>
The problem lies with your variable rowTemplate. Get rid of the $ and it should work.
var rowTemplate = $('<tr><td data-id="id"></td><td data-id="name"></td><td data-id="geburtsort"></td><td data-id="geburtsdatum"></td><td data-id="favorite"></td></tr>');
rowTemplate.find("[data-id=id]").text("bcd");
Test it out here: https://jsfiddle.net/Lwmu4p6q/
I am not quite sure why that is the case, though. I think it is problematic because of jQuery. You can still use variables starting with a dollar sign, but when you start cascading with jQuery functions, it doesn't seem to work.
EDIT: Another way to do it would be to manually "build up" the row.
Instead of parsing the HTML with jQuery like rowTemplate = $('...'); and then manipulating it with jQuery selectors you could do it like this with vanilla JavaScript:
var outputHTML = "";
for (var i = 0; i < array.length; i++) { // i for the rows
var newRow = "<tr>";
for (var j = 0; j < array[i].length; j++) { // j for the colums
newRow += "<td>" + array[i][j] + "</td>";
}
outputHTML += newRow + "</tr>";
}
I would suggest using let instead of var if possible. And I would argue that this version might perform faster, but the difference, if existent at all, would only matter with really big tables. It depends on the way jQuery selectors and text() has been implemented, though.
EDIT 2:
Check https://jsfiddle.net/Lv9vdv8u/ for the second version.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to add input fields to a page dynamically, when a user clicks a button.
I have the following code, which is being called, but doesn't work as expected
var a= document.getElementsByTagName("button");
a[0].addEventListener("click", clicked);
function clicked(){
var input = document.createElement("input");
document.appendChild("input");
}
The error I am facing is this:
"error"
"TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
at HTMLButtonElement.clicked (sofodipabe.js:5:12)"
What is causing this issue?
Do you wish to use jQuery? If you are using jQuery you can follow my easy solution below other wise #kira-sen had provided good solution.
Here is the fiddle you may look at.
HTML
<input type="text" id="n" placeholder="How may elements to add">
<button id="addElements">Add elements</button> <br>
<div id="addElementsHere">
</div>
JS
$("#addElements").click(function(e){
var n = parseInt($(this).siblings("#n").val());
for(var i = 0; i<n; i++){
$("#addElementsHere").append("<input class='xyz' type='text' placeholder=' Enter value for input number " + (i + 1) + "' id='inp-"+(i+1)+"'>");
}
});
Hope this helps.
Try This
// Creating 10 Input textboxes
var div = document.createElement('div');
for(var i = 0; i < 10; i++) {
var inputElement=document.createElement('input');
inputElement.setAttribute('type','text');
inputElement.setAttribute('id','id' + i);
inputElement.value='My Value ' + (i+1);
div.appendChild(inputElement);
}
document.getElementById("container").appendChild(div);
// Adding class
var inputElements = document.querySelectorAll('input');
for(var i=0; i < inputElements.length; i++) {
inputElements[i].className='MyClass' + i;
// Getting value
console.log(inputElements[i].value);
}
<div id="container"></div>
You can use this as an example to do what you want.
var container = document.querySelector('#container')
for (var i = 0; i < 10; i++) {
var input = document.createElement('input') // create a new element
input.classList.add('input') // Add .input class to the created element
input.placeholder = 'Input ' + i // set an attribute
input.id = 'input' + i // set the ID
container.append(input) // Append the element to a parent element (container in this case)
}
.input {
width: 100%;
}
<div id="container"></div>
What I'm trying to do is pretty simple: Add a 1x20 table of input cells inside a div.
I created a JavaScript function
var tableHTML = function(attributes, rows, columns)
{
var retHTML = "<table " + attributes + ">";
for (var i = 0; i < rows; ++i)
{
retHTML += "<tr>";
for (var j = 0; j < columns; ++j)
retHTML += "<td> </td>";
retHTML += "</tr>";
}
return (retHTML + "</table>retHTML");
}
to give me the HTML for a table with a specified dimensions and attributes. Then, in the body of my HTML, I put
<div class="inner_div" id="input_table">
<!-- div to house the table -->
</div>
<script type="text/javascript">
document.getElementById("input_table").innerHTML += tableHTML("id=\"input_table\" type=\"input\"", 1, 20);
</script>
which I thought would accomplish the task, but hasn't. I think this is because I'm trying to assign a string object to an HTML object. I kinda assumed that an implicit cast would be made. Anyways, I'm wondering if anyone has a "quick fix" to my problem. I would prefer not to redo my entire approach to the problem, but I also wouldn't mind someone informing me of the proper way to do the type of thing I'm trying to do -- using JavaScript to fill in page HTML on load.
Here's my take on this. I'm learning functional programming, so I do a bunch things here that might seem like their a waste of coding, but here's the concept:
Get the dimensions
Create a single row
Copy that row to make the table
After that return the table.
If you want to add id's, class's, etc... work with the DOM element returned by makeTable.
// Makes a single row
var makeRow = function(_columns) {
var row = document.createElement('tr');
var cell = document.createElement('td');
var cols = _columns;
while (cols) {
row.appendChild(cell.cloneNode(true));
cols--;
}
return row;
}
// Makes a table
var makeTable = function(_rows, _columns) {
var table = document.createElement('table');
var row = makeRow(_columns);
var rows = _rows;
while (rows) {
table.appendChild(row.cloneNode(true));
rows--;
}
return table;
}
I tried your code and it works: the table is generated and obviously empty
But be carrefull: if you do this, you will have two elements with the same ID (input_table)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
So I want to generate a list from an Array I wrote the following code:
function list() {
table = new Array("Rabat", "Casablanca", "Marrakech", "Fes", "Tanger", "Agadir");
document.write('<select id="list1" size=6><option value="Rabat">Rabat</option><option value="Casablanca">Casablanca</option></select>');
}
It works but I'm wondering if there's a better coding
You can use a loop to go through all items in the list:
// you can use this instead of the new Array() syntax:
var table = ["Rabat", "Casablanca", "Marrakech", "Fes", "Tanger", "Agadir"];
var select = '<select id="list1" size="6">';
for (var i=0; i<table.length; i++) {
select += '<option value="' + table[i] + '">' + table[i] + '</option>';
}
select += '</select>';
document.write(select); //you should probably not use document.write though...
Usually it is better not to use document.write though. Instead, you should try selecting the element you want to append to, and then add the text to that.
HTML:
<select id="list1" size="6"></select>
JS:
function list() {
var i,
table = ["Rabat", "Casablanca", "Marrakech", "Fes", "Tanger", "Agadir"],
select = document.getElementById('list1'),
out;
for (i = 0; i < table.length; ++i) {
out += "<option value='" + table[i] + "'>" + table[i] + "</option>";
}
select.innerHTML = out;
}
FIDDLE:
http://jsfiddle.net/Z9XKp/
you can loop over the array and make your string rather than writing same code again and again .
var list="";
for(i=0;i<table.length;i++){
var val=table[i];
list+="<option value='"+val+"'>"+val+"</option";
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Looking for any PHP, Jquery, javascript solution to take data separated by commas and turn it into an unordered list.
To explain further, I have imported a CSV file into wordpress and one element block contains lots of data that is comma separated and I need it to display as a list.
All help is appreciated!
In PHP
$list = 'item1,item2,item3,item4';
$list = explode(',', $list);
shuffle($list);
$html = '<ul>';
foreach($list as $item) {
$html .= '<li>' . $item . '</li>';
}
$html .= '</ul>';
print $html;
In JavaScript
var list = 'item1,item2,item3,item4';
list = list.split(',');
list.sort(function() { return 0.5 - Math.random() });
var html = '<ul>';
for(var i=0; i<list.length; i++) {
html += '<li>' + list[i] + '</li>';
}
html += '</ul>';
There are cleaner ways to write this, but hopefully this will give you an idea of how it can be done using jQuery.
$(function(){
$csv = $("#csv")
items = $csv.text().split(",")
$csv.replaceWith($("<ul/>"))
items.forEach(function(item){
$("ul").append("<li>"+item+"</li>")
})
})
And here's the fiddle: http://jsfiddle.net/JmwDw/
HTML
<ul id="ul-test">
</ul>
JavaScript
var CSV = "a,b,c,d,e";
var arrCSV = CSV.split(','),
ul = document.getElementById("ul-test");
for (var i = 0, len = arrCSV.length; i < len; i++) {
var li = document.createElement("li");
var text = document.createTextNode(arrCSV[i]);
li.appendChild(text);
ul.appendChild(li);
}
JSFiddle
I have a code to populate a table using Javascript as:
var myResponse = document.getElementById("jsonPlaceHolder");
myResponse.innerHTML += "<table border=1> <tr> <td> User Id </td> <td> Question </td> <td> Link Question </td> </tr>";
for (var i = 0; i < 25; i++) {
myResponse.innerHTML += "<tr>"
myResponse.innerHTML += "<td>" + jsonObj[i]["user_id"] + "</td>";
myResponse.innerHTML += "<td>" + jsonObj[i]["text"] + "</td>";
myResponse.innerHTML += "</tr>"
}
myResponse.innerHTML += "</table>";
Problem with this code is when I run this table is not continued inside for loop. If I add
myResponse.innerHTML += "<table><tr>"
inside my for loop, table is created. Isn't this bit odd?,
since i am using += to add to current innerHTML of the DOM element.
One of the most misunderstood thing about innerHTML stems from the way the API is designed. It overloads the + and = operators to perform DOM insertion. This tricks programmers into thinking that it is merely doing string operations when in fact innerHTML behaves more like a function rather than a variable. It would be less confusing to people if innerHTML was designed like this:
element.innerHTML('some html here');
unfortunately it's too late to change the API so we must instead understand that it is really an API instead of merely an attribute/variable.
When you modify innerHTML it triggers a call to the browser's HTML compiler. It's the same compiler that compiles your html file/document. There's nothing special about the HTML compiler that innerHTML calls. Therefore, whatever you can do to a html file you can pass to innerHTML (the one exception being that embedded javascript don't get executed - probably for security reasons).
This makes sense from the point of view of a browser developer. Why include two separate HTML compilers in the browser? Especially considering the fact that HTML compilers are huge, complex beasts.
The down side to this is that incomplete HTML will be handled the same way it is handled for html documents. In the case of elements not inside a table most browsers will simply strip it away (as you've observed for yourself). That is essentially what you're trying to do - create invalid/incomplete HTML.
The solution is to provide innerHTML with complete HTML:
var htmlString = "<table border=1> <tr> <td> User Id </td> <td> Question </td> <td> Link Question </td> </tr>";
for (var i = 0; i < 25; i++) {
htmlString += "<tr>"
htmlString += "<td>" + jsonObj[i]["user_id"] + "</td>";
htmlString += "<td>" + jsonObj[i]["text"] + "</td>";
htmlString += "</tr>"
}
htmlString += "</table>"
myResponse.innerHTML += htmlString;
Use the DOM API to manipulate the DOM:
var myResponse = document.getElementById("jsonPlaceHolder");
var table = document.createElement('table'),
headings = ["User ID", "Question", "Link Question"];
table.style.border = "1";
var r = table.insertRow(-1);
for (var i = 0; i < 3; i++) {
(function(){
return r.insertCell(-1);
})().innerHTML = heading[i];
}
for (var i = 0; i < 25; i++) {
r = table.insertRow(-1);
var userid = r.insertCell(-1),
text = r.insertCell(-1);
userid.innerHTML = jsonObj[i]["user_id"];
text.innerHTML = jsonObj[i]["text"];
}
myResponse.appendChild(table);