How to add a placeholder to a radio button? [duplicate] - javascript

This question already has answers here:
How to put text inside radio button?
(2 answers)
Closed 5 years ago.
I was wondering if there was a way to add a placeholder to a radio button. I tried to do it, code below, but it did not work. I want the first button to have the placeholder value "1", and the second to have the value "2" and so on. Is there a way to do that? I mean that the button, when the user looks at it, will have number "1" in it.
function drawTable(daysInMonth) {
var cellsToDraw = daysInMonth;
var table = document.getElementById("table");
table.innerHTML = "";
for (r = 0; r < (daysInMonth / 7); r++) {
var newRow = document.createElement("tr");
table.appendChild(newRow);
for (c = 0; c < 7 && cellsToDraw > 0; c++) {
var newCell = document.createElement("input");
newCell.setAttribute("type", "radio");
newCell.setAttribute("name", "day");
newCell.setAttribute("placeholder", 1)
newRow.appendChild(newCell);
newCell.innerHTML = //add the numbers here?
cellsToDraw--;
}
}
}
CSS:
input[type=radio] {
border: 1px solid;
padding: 0.5em;
-webkit-appearance: none;
width: 95px;
height: 100px;
margin-right: -4px;
margin-top: -8px;
}
All help is appriciated!

Radio buttons don't support placeholders, and there wouldn't be any space to render one in anyway.
It sounds like you are confusing placeholders with labels (see this article).
Use a LABEL element instead.
Aside: INPUT elements are not allowed to be children of TR elements. Only TD and TH elements may be children of a TR.
function drawTable(daysInMonth) {
var cellsToDraw = daysInMonth;
var table = document.createElement("table");
document.body.appendChild(table);
for (r = 0; r < (daysInMonth / 7); r++) {
var newRow = document.createElement("tr");
table.appendChild(newRow);
for (c = 0; c < 7 && cellsToDraw > 0; c++) {
var newCell = document.createElement("td");
var input = document.createElement("input");
var label = document.createElement("label");
input.setAttribute("type", "radio");
input.setAttribute("name", "day");
label.appendChild(input);
label.appendChild(document.createTextNode("1"));
newCell.appendChild(label);
newRow.appendChild(newCell);
cellsToDraw--;
}
}
}
drawTable(30);

instead of innerHTML you can set value
newCell.value = c

Related

Trying to add a select element to a table dynamically but its not showing up in the cell

I've already managed to successfully insert various elements dynamically into separate cells of a table per row such as label, checkbox and input text type. However, when I try to insert a select element with the options it doesn't show up in the row and also, all the other elements stop appearing as well.
As you can see, I'm using Javascript HTML DOM to add (append) the elements to the parents - all elements appear in the respective cells per row up until I try to append the select element, then nothing shows in the table, no elememnts, no rows, cells, nothing.
Can anyone enlighten me here - is it a style problem?
Thanks.
Here is my CSS, HTML and SCRIPT codes as follows. Questions is a 2 dim array to populate the elements appended to the cells
function fillTable(questions) {
var questsLength = questions.length;
for (var i = 0; i < questsLength; i++) {
var row = document.createElement("tr");
row.setAttribute = ("id", i);
var col1 = document.createElement("td");
var col2 = document.createElement("td");
var col3 = document.createElement("td");
var col4 = document.createElement("td");
var qno = document.createElement("label");
qno.innerHTML = i + 1;
col1.appendChild(qno);
row.appendChild(col1);
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
col2.appendChild(checkbox);
row.appendChild(col2);
var question = document.createElement("input");
question.type = "text";
question.value = questions[i][1];
col3.appendChild(question);
row.appendChild(col3);
var questOpts = document.createElement("select");
var alphabet = ["A", "B", "C", "D", "E", "F"];
for (var j = 0; j < alphabet.length; j++) {
var option = document.createElement("option");
option.value = alphabet[j];
option.innerHTML = alphabet[j];
questOpts.appendChild(option);
}
col4.appendChild(questOpts);
row.appendChild(col4);
var tab = document.getElementById("bdy");
tab.appendChild(row);
}
}
.fixTableHead {
overflow-y: auto;
height: 110px;
position: relative;
top: 100px;
}
.fixTableHead th {
position: sticky;
top: 0;
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
padding: 8px 15px;
border: 2px solid #529432;
background: #ffffff;
}
th {
background: #ABDD93;
}
<div class="fixTableHead">
<table id="bdy">
<tr>
<th>No</th>
<th>Select</th>
<th>Question</th>
<th>Answer options</th>
<th>Question type</th>
</tr>
</table>
</div>

Create Recursive Form Elements

I'm creating a homework calculator. I need to recursively create form elements, and found out how to make a recursively creating table. How do I turn the spaces in that table into form elements that create themselves recursively? If this isn't clear, please tell me.
<table id="xTable"></table>
<script>
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
cell.textContent = "I want to make this into a recursive form creator ";
}
}
</script>
<style>
td {
border: 2px ridge #333;
text-align: center;
}
</style>
It's rather simple, just create the elements you want to insert into the cells with document.createElement, then set the properties you want them to have and use cell.appendChild to place them into the cell.
This example creates <input type="text"> elements:
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
var input = document.createElement('input');
input.type = 'text';
input.name = 'input_r' + i + '-c' + j;
cell.appendChild(input);
}
}
td {
border: 2px ridge #333;
text-align: center;
}
<table id="xTable"></table>

using a for loop to create tr's and td's in a table element \\ unable to parse results from td's

I am creating a table that creates tr's and td's within a table. The table with loop through a subtraction calculation and create a column of the results from the for loop. When I try to add the next column it does not parse the calculations but continues to perform calculations
for (i=foo; i<bar+1; i++)
{
var tableNode = document.getElementById('tableID');
var trNode = document.createElement('tr');
var trValue = '';
var tdNode = document.createElement('td');
var tdValue = parseFloat(i) + parseFloat(500); //this is calculating 500 and not concatenating 500 for every iteration.
trNode.innerHTML = trValue;
tdNode.innerHTML = tdValue;
tableNode.appendChild(trNode);
trNode.appendChild(tdNode);
}
The goal is to do using a for loop that populates the tr's and td's
1 500
2 500
3 500
This should work:
let foo = 1,
bar = 3;
for (let i = foo; i <= bar; i++) {
var tableNode = document.getElementById("tableID");
let trNode = document.createElement("tr");
let trValue = "";
let tdNode = document.createElement("td");
let tdValue = parseFloat(i) + ' ' + parseFloat(500);
trNode.innerHTML = trValue;
tdNode.innerHTML = tdValue;
trNode.appendChild(tdNode);
tableNode.appendChild(trNode);
}
table tr td {
border: 1px solid #ccc;
}
<table id="tableID"></table>
If you want to concatenate parseFloat(i) and parseFloat(500), do:
var tdValue = parseFloat(i) + " " + parseFloat(500);
instead of parseFloat(i) + parseFloat(500) because this will add the float values and tdValue will be the sum (of type number).
Note the " " (string containing a space) in the middle which will consider the elements to be concatenated as strings and the result of the concatenation to be of type string.
<table> & for loops
If you want to generate a <table> with a for loop you should use two for loops -- first loop is for rows and the second loop is for cells for each row. The following demo has the following:
A <form> that has:
An <input> to enter the number of rows.
An <input> to enter the number of cells per row.
button to trigger the click event that calls the function generateTable().
The <form> and all of its form controls are accessed by using HTMLFormControlsCollection API.
The methods .insertRow() and .insertCell() will automatically create an element and append it.
The <form> and all that's related to it are optional of course, it's just added for demonstration purposes. The loops can be used alone by just assigning numbers to variables rowQty and celQty.
Demo
/*
Optional
*/
var ui = document.forms[0].elements;
var btn = ui.btn;
btn.onclick = generateTable;
/*
Required
*/
function generateTable(e) {
var table = document.getElementById('T0');
/*
if used without the <form>
replace the next two lines with:
*/
//var rowQty = {any integer}
//var celQty = {any integer 2 or greter}
var rowQty = ui.rowData.value;
var celQty = ui.celData.value;
for (let i = 0; i < rowQty; i++) {
var tr = table.insertRow(i);
for (let j = 0; j < celQty; j++) {
var td = tr.insertCell(j);
if (j === 0) {
td.textContent = i + 1;
} else if (j === 1) {
td.textContent = "500";
} else {
td.textContent = " ";
}
}
}
}
table {
border-collapse: collapse;
table-layout: fixed;
}
table,
td {
border: 1px solid #000;
text-align: right;
}
td {
min-width: 3ch;
max-width: 150px;
}
td:first-of-type {
width: 3ch;
text-align: center;
}
input {
display: inline-block;
text-align: center;
width: 5ch;
}
<!-- Optional -->
<form id='ui'>
<label for='rowData'>Rows: </label>
<input id='rowData' type='number' min='1' max='10' value='1'>
<label for='celData'>Cells per Row: </label>
<input id='celData' type='number' min='2' max='10' value='2'>
<button id='btn' type='button'>GO</button>
</form>
<!-- Required -->
<table id='T0'></table>

How to create a table using a loop?

The individual table rows are giving me a problem. I have created what I want using divs but I need to use a table instead of divs. My table has 220 cells, 10 rows, and 22 columns. Each cell has to have the value of i inside the innerHTML. Here is similar to what i want using Divs ( although the cell height and width does not have to be set ):
<!DOCTYPE html>
<html>
<head>
<style>
#container{
width:682px; height:310px;
background-color:#555; font-size:85%;
}
.cell {
width:30px; height:30px;
background-color:#333; color:#ccc;
float:left; margin-right:1px;
margin-bottom:1px;
}
</style>
</head>
<body>
<div id="container">
<script>
for( var i = 1; i <= 220; i++ ){
document.getElementById( 'container' ).innerHTML +=
'<div class="cell">' + i + '</div>'
}
</script>
</div>
</body>
</html>
http://jsfiddle.net/8r6619wL/
This is my starting attempt using a table:
<script>
for( var i = 0; i <= 10; i++ )
{
document.getElementById( 'table' ).innerHTML +=
'<tr id = "row' + i + '"><td>...</td></tr>';
}
</script>
But that code somehow dynamically creates a bunch of tbody elements. Thanks for help as I newb
You can do this with nested loops - one to add cells to each row and one to add rows to the table. JSFiddle
var table = document.createElement('table'), tr, td, row, cell;
for (row = 0; row < 10; row++) {
tr = document.createElement('tr');
for (cell = 0; cell < 22; cell++) {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = row * 22 + cell + 1;
}
table.appendChild(tr);
}
document.getElementById('container').appendChild(table);
Alternatively, you can create an empty row of 22 cells, clone it 10 times, and then add the numbers to the cells.
var table = document.createElement('table'),
tr = document.createElement('tr'),
cells, i;
for (i = 0; i < 22; i++) { // Create an empty row
tr.appendChild(document.createElement('td'));
}
for (i = 0; i < 10; i++) { // Add 10 copies of it to the table
table.appendChild(tr.cloneNode(true));
}
cells = table.getElementsByTagName('td'); // get all of the cells
for (i = 0; i < 220; i++) { // number them
cells[i].innerHTML = i + 1;
}
document.getElementById('container').appendChild(table);
And a third option: add the cells in a single loop, making a new row every 22 cells.
var table = document.createElement('table'), tr, td, i;
for (i = 0; i < 220; i++) {
if (i % 22 == 0) { // every 22nd cell (including the first)
tr = table.appendChild(document.createElement('tr')); // add a new row
}
td = tr.appendChild(document.createElement('td'));
td.innerHTML = i + 1;
}
document.getElementById('container').appendChild(table);
Edit - how I would do this nowadays (2021)... with a helper function of some kind to build dom elements, and using map.
function make(tag, content) {
const el = document.createElement(tag);
content.forEach(c => el.appendChild(c));
return el;
}
document.getElementById("container").appendChild(make(
"table", [...Array(10).keys()].map(row => make(
"tr", [...Array(22).keys()].map(column => make(
"td", [document.createTextNode(row * 22 + column + 1)]
))
))
));
There are a lot of ways to do this, but one I've found to be helpful is to create a fragment then append everything into it. It's fast and limits DOM re-paints/re-flows from a loop.
Take a look at this jsbin example.
Here's the modified code:
function newNode(node, text, styles) {
node.innerHTML = text;
node.className = styles;
return node;
}
var fragment = document.createDocumentFragment(),
container = document.getElementById("container");
for(var i = 1; i <= 10; i++) {
var tr = document.createElement("tr");
var td = newNode(document.createElement("td"), i, "cell");
tr.appendChild(td);
fragment.appendChild(tr);
}
container.appendChild(fragment);
You can modify whatever you want inside the loop, but this should get you started.
That's because the DOM magically wraps a <tbody> element around stray table rows in your table, as it is designed to do. Fortunately, you can rewrite your loop in a way that will add all of those table rows at once, rather than one at a time.
The simplest solution to achieve this would be to store a string variable, and concatenate your rows onto that. Then, after you've concatenated your rows together into one string, you can set the innerHTML of your table element to that one string like so:
<script>
(function() {
var rows = '';
for( var i = 0; i <= 10; i++ )
{
rows += '<tr id = "row' + i + '"><td>...</td></tr>';
}
document.getElementById( 'table' ).innerHTML = rows;
}());
</script>
Here's a JSFiddle that demonstrates what I've just written. If you inspect the HTML using your browser's developer tools, you'll notice that one (and only one) tbody wraps around all of your table rows.
Also, if you're wondering, the odd-looking function which wraps around that code is simply a fancy way of keeping the variables you've created from becoming global (because they don't need to be). See this blog post for more details on how that works.
please check this out.
This is a very simple way to create a table using js and HTML
<body>
<table cellspacing="5" >
<thead>
<tr>
<td>Particulate count</td>
<td>Temperature</td>
<td>Humidity</td>
</tr>
</thead>
<tbody id="xxx">
</tbody>
</table>
<script>
for (var a=0; a < 2; a++) {
var table1 = document.getElementById('xxx');
var rowrow = document.createElement('tr');
for ( i=0; i <1; i++) {
var cell1 = document.createElement('td');
var text1 = document.createTextNode('test1'+a);
var cell2 = document.createElement('td');
var text2 = document.createTextNode('test2'+a);
var cell3 = document.createElement('td');
var text3 = document.createTextNode('test3'+a);
cell1.appendChild(text1);
rowrow.appendChild(cell1);
cell2.appendChild(text2);
rowrow.appendChild(cell2);
cell3.appendChild(text3);
rowrow.appendChild(cell3);
}
table1.appendChild(rowrow);
}
</script>
</body>
</html>

Distinguish td's using javascript

I am creating a table, two rows, and two cells in each row in my code. For this purpose, I've got the following code:
var t = document.createElement('table');
document.body.appendChild(t);
for (var x = 0; x <= 1; x++) {
var tr = document.createElement('tr');
t.appendChild(tr);
for (var y = 0; y <= 1; y++) {
var td = document.createElement('td');
tr.appendChild(td);
}
}
Now, I need to create a text node in the first cell and create a a element in the second cell. How would I do that?
It's actually more code to do a "two-step" loop, than to write it out in full:
var t = document.createElement('table'),
trs = [document.createElement('tr'),document.createElement('tr')],
tds = [
[document.createElement('td'),document.createElement('td')],
[document.createElement('td'),document.createElement('td')]
];
trs[0].appendChild(tds[0][0]); trs[0].appendChild(tds[0][1]);
trs[1].appendChild(tds[1][0]); trs[1].appendChild(tds[1][1]);
t.appendChild(trs[0]); t.appendChild(trs[1]);
// now append more stuff here to the tds
document.body.appendChild(t); // do this last - it's better
var t = document.createElement('table');
document.body.appendChild(t);
for (var x = 0; x <= 1; x++) {
var tr = document.createElement('tr');
t.appendChild(tr);
for (var y = 0; y <= 1; y++) {
var td = document.createElement('td');
tr.appendChild(td);
if(y == 0){
alert("here");
var a = document.createElement('A');
td.appendChild(a);
alert("here");
}
else{
var div = document.createElement('div');
td.appendChild(div);
//Create text node
}
}
}
Inside your loop check if y == 0, if it is then you are at your first td therefore you create a link.
If y == 1 you are at the second td therefore you create textnode
Replace div with whatever you want.
inside your second loop just check for if (y == 0) then create text inside the td and if (y == 1) then create an a inside the td.
another way would be to just define the table in text.
eg:
var t = document.createElement('table');
t.innerHTML = "<tr><td>text</td><td><a href='#'>link</a></td></tr><tr><td>text</td><td><a href='#'>link</a></td></tr>";

Categories

Resources