Use jQuery insertAfter in existing function that appends table - javascript

Here is what I have so far: http://jsfiddle.net/JEAkX/1/
I am trying to get the appended cells to come after the last tr. Furthermore, I am attempting to change the appendTable(id) function so that the output cells have their content inside an <input> field like the original cells.
For the <input> addition I have tried:
Adding the input field code <input type='text' size='1' value='subset[i++]' /> at various point with no luck I also tried it in another location but changed the value to value='c'.
For append after last tr I have tried:
Using jQuery and .insertAfter('#alphabetTable tbody>tr:last') I added it to various parts of the cell.appendChild(document.createTextNode(subset[i++])); line but had no luck..probably the wrong placement?
I feel like I am sort of on the right track but lack the Javascript knowledge to know exactly where to insert the code and if surrounding code needs change.

It'll be easier with JQuery but here's a hint:
function appendTable(id)
{
var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
var i = 0;
var html = '<tr>';
for(i=0;i<4;i++){
html += '<td><input type="text" size="1"/></td>';
}
html += '</tr>';
tbody.innerHTML += html;
}

Jquery:
var $tbody = $('#mytableid tbody:eq(0)');
var $tdLen = $('#mytableid tbody:eq(0) tr:eq(0) td').length; // cell length in row
$("<tr>").appendTo($tbody);
//append cells to row with input text
for (var i=0;i<$tdLen;i++){
var inp = $("<input>").attr("type","text").attr("name","text"+i).val(i);
var tdTemo = $("<td>");
inp.appendTo(tdTemo);
tdTemo.appendTo("tr:last");
}
this script will append row to table and add 4cells contain input type text :)

Related

How to add new lines after HTML elements

I have a simple method for adding input boxes after a button is clicked. The goal of this method is to generate a set of input boxes with a newline inserted after each div.
In the screenshot above you can see that the divs are spaced properly. However, when the add_more button is clicked the generated inputs do not come out properly.
Expected:
The code should generate new input boxes like so:
<div>
Key Term 2: <input id="el2" type="text" value=""> <br>
</div>
<br>
Actual:
function add_more() {
// we've added more inputs.
addMore = true;
// set html generated to false, because new inputs have been added.
htmlGenerated = false;
// increment the number of inputs.
numberOfInputs++;
//fetch the input boxes.
inputs = document.getElementById("inputBoxes");
// create newline
br_key = document.createElement("br");
// create newline
br_description = document.createElement("br");
//create a new row for a key term.
row = document.createElement("div");
// set the key term text.
row.innerHTML = "Key Term ";
row.innerHTML += numberOfInputs;
row.innerHTML += " :";
// create the input for the key.
key = document.createElement("input");
key.setAttribute("id", "el" + numberOfInputs);
//add the key to the row.
row.appendChild(key);
row.after(br_key);
//create a row for the new description.
row2 = document.createElement("div");
// set the description text.
row2.innerHTML = "Description "
row2.innerHTML += numberOfInputs;
row2.innerHTML += " :";
// create the description input
description = document.createElement("input");
description.setAttribute("id", "dl" + numberOfInputs);
// add the description to the row.
row2.appendChild(description);
row2.after(br_description);
// add the rows for the key and the description to the inputBoxes.
inputs.appendChild(row);
inputs.appendChild(row2);
}
<div>Key Term 5 :<input id="el5"></div>
Any help figuring out this issue would be greatly appreciated. Thanks.
Your issue here is essentially incorrect HTML, CSS. I'd implement your inputs, etc. like this:
.full-width-label {
display:block;
}
<label class="full-width-label" for="1">Label</label>
<input type="text" id="1"/>
There are multiple ways to achieve the above, this is just one of your options but now you no longer need to embed the look into the HTML and the format of your HTML (line breaks) is independent of your look.
You might want to look into an off the shelf solution for these kinds of things, like Bootstrap or Tailwind
You can use make it in a simple way
HTML
add this jquery cdn
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<button type="button">Click Here</button>
<div class="appendDiv">
</div>
Js
$(document).ready(function (){
var button = document.getElementsByTagName('button');
var appendDiv = document.getElementsByClassName('appendDiv');
var key = 1;
var descKey = 1;
$('button').click(function(event){
event.preventDefault();
$(appendDiv).append('<div class="child"><div class="grand-child"><label>Key Form :'+ ' '+(++key)+'</label><input type="text" value=""/></div><div class="grand-child"></div><label>Description :'+ ' '+(++descKey )+'</label><input type="text" value=""/></div>');
})
})

Add element works but clears input value

I have a script below that adds an element to my form, another text input field. It adds the new text input field but if I type something into the first one then add a new field it removes the input text from the first one.
I cant see where im going wrong here, im fairly new to JavaScript so please go easy :)
function addAnother() {
var id = 1;
var elemebt = document.getElementById('quest');
var number = elemebt.getElementsByTagName('*').length;
var add = number + 1;
var element = '<input type="text" name="question[]" id="quest'+ add +
'" placeholder="Example: What previous experiance do you have?" class="form-control" id="cloan"><a id="name'+
add +'" onClick="removeEle('+ add +')">Remove</a>';
document.getElementById('quest').innerHTML += element;
}
In JavaScript, the following two statements are practically identical:
str = str + ' more text ';
str += ' more text ';
The key point here is that in the end, the value of str is COMPLETELY OVERWRITTEN.
In your case, that means the innerHTML of the "quest" element is overwritten and the browser completely recreates it's children nodes, thus reseting any state and input values.
To overcome this, you can use the appendChild method but you first need to create the element to append. The easiest way to do that given you have a string of your HTML is to inject that string into a dummy element using the innerHTML property:
var target = document.getElementById('target');
var tDiv = document.createElement('div');
var htmlString = '<input type="text"></input>';
tDiv.innerHTML = htmlString;
target.appendChild(tDiv.children[0]);
<div id="target">Keep my content safe!</div>

.onchange or .onclick and checkbox value to JS script

I have an array of checkboxes group into class='year'. I would like to call a function in JS when a checkbox is checked.
The html is,
<table class="inner" id="searchTable">
<search>Exam Type:<th>
<?php
foreach($exams as $key=>$value):
echo "<tr><td class='left'><input type='checkbox' class='year' id='$key' name='$key' value='$value'
if ($category['selected'])
{
echo ' checked';
}
> $value</td></tr>";
endforeach; ?>
</table>
This table is inside a form. but I am too worried about the form at the moment.
The JS should create a table with a row when any checkbox is checked.
function yearTable(){
var table = document.getElementById("searchYear");
var row = document.createElement("tr");
var cell = document.createElement("td");
var empty = document.createTextNode("year.value");
/*var empty = document.createTextNode("");*/
cell.appendChild(empty);
row.appendChild(cell);
table.appendChild(row);
}
document.getElementByClassName('year').onchange = yearTable;
I have tried using .onchange and .clicked but neither do anything when a box is checked.
Also I need the value checked in the JS.
I tried year.value but that doesn't work. Prviously I has a select options menu with id = 'exam' and I was able to get the value using exam.value but I can't figure out how to do soemthing equivalent for these checkboxes.
Any help would be greatly appreciated.
Thanks
While an html document may contain only one element with a specific id, there can be several elements with the same class.
So, there is no such a function as document.getElementByClassName. There is a function document.getElementsByClassName, and it returns an array of elements, so could call that function and then iterate over its return value, setting the needed callbacks.
Also, the code you posted must have thrown an exception at this line:
document.getElementByClassName('year')
So if you looked at developer tools in Chrome or Firebug in Firefox, you would probably see an error.
Got it,
function yearTable(){
var year = this.value;
var table = document.getElementById("searchYear");
var row = document.createElement("tr");
var cell = document.createElement("td");
if (this.checked){
var empty = document.createTextNode(year);
}
cell.appendChild(empty);
row.appendChild(cell);
table.appendChild(row);
}
var checkboxes = document.getElementsByClassName('year');
for(var index in checkboxes){
checkboxes[index].onchange = yearTable;
}
Thanks

How to create an input field and then prepopulate the field with

Please no jquery.
I've seen several examples of this where the input field already exists on the page before you update it, but I'd like to dynamically create the input field and then populate it with information available from the page (hence current_value variable defined above this code snippet):
for (i=0; i<tables.length; i++) {
(function(i) {
var sp = document.createElement('span');
var act_table = document.createElement('table');
act_table.id = 'act-tests-' + i;
act_table.style.display = 'none';
var test_name_input = document.createElement('tr');
test_name_input.innerHTML = '<tr><td width="100px">Name</td><td><input type="text" class="wideValue testName input"></td></tr>';
test_name_input.setAttribute('value', current_rule);
act_table.innerHTML ='<tbody><tr>LOTS OF TABLE ROWS HERE</tr></tbody>';
act_table.insertBefore(test_name_input,act_table.firstChild);
sp.appendChild(act_table);
}
The field is being shown but not populated with my current_value.
Any help greatly appreciated.
In your example you set an attribute to the tr, instead of the created input field.
try to do this:
document.getElementsByClassName("input")[you_index].setAttribute("value", current_value);
Here an example: http://jsfiddle.net/35g0ks0t/

Dynamically create a table from user input

I am taking user input from a form and trying to create a table from that input. The input should determine the number of rows and columns. I have tried the following but I am getting nothing. I am a bit stumped. Any help appreciated.
JS
function makeChart(){
var table = document.createElement("table");
var taskName = document.getElementById("taskname").value + "</br>";
var numDays = document.getElementById("days").value + "</br>";
var howOften = document.getElementById("times").value + "</br>";
var rows=table.insertRow(howOften);
var cols=rows.insertCell(numDays);
document.getElementById("holdTable").appendChild(table);
table.appendChild(rows);
table.appendChild(cols);
}
HTML
<div id="holdTable">
<form id="chartInput">
<label for="taskname">Task</label>
<input id="taskname" type="text" placeholder="Enter the task name here"> <br>
<label for="days">How many days</label>
<input id="days" name="days" type="number" min="1" max="7"> <br>
<label for="times">How many times a day</label>
<input id="times" name="times" type="number" min="1" max="4"> <br>
<input id="createChart" type="button" value="Make the chart" onClick="makeChart();"> <br>
</form>
</div>
I think you need to use loop.
for(var i = 1;i<=howOften;i++)
{
var row = table.insertRow(-1)
for(var i = 1;i<=numDays;i++)
{
row.insertCell(-1)
}
table.appendChild(row);//edited
}
Try using this in place of this 2 lines:
var rows=table.insertRow(howOften);
var cols=rows.insertCell(numDays);
EXPLANATION
insertRow function inserts new table row(<tr>) in at index position specified in brackets. It inserts only one row. So if index is 0 <tr> will be appended to the beggining of the table as a first row. Similarly -1 appends <tr> as the last row in the table.
insertCell function inserts cell(<td>) in at index position of the row(<tr>). Same as above -1 means it adds new cell at the last position in the row.
Each row than has to be appended to the table or stored in an array for later use therefore I added table.appendChild(row); which adds each consecutive row to the array.
table.insertRow and tableRow.insertCell take, as their parameters, the index at which you wish to do the insertion. You are, instead, passing a string which contains your field values appended to an HTML BR tag (a malformed one at that).
Furthermore, to add text to an element you need to create text nodes with document.createTextNode and append those nodes to the element in question.
Finally, cols should be a child of rows, not of table. So your line, table.appendChild(cols) is in error as well.
Beyond those comments, I cannot go further. I am not sure what exactly you're looking for in the outputted table structure. It seems to me you are wanting one row with two columns, but Dharman's answer shows that he reads it as you wanting multiple rows. Consider updating your question with some markup showing the desired table.
Edit: Using your comment for more information, I wrote the following code demo for you to try: http://jsfiddle.net/Kkb7n/ . For the sake of demonstration, I have it use the "task name" as the text content of the created cells.
Modified JS in case JSFiddle is down:
var makeChart = function () {
var table = document.createElement('table'),
taskName = document.getElementById('taskname').value,
numDays = document.getElementById('days').value, //columns
howOften = document.getElementById('times').value, //rows
row,
r,
col,
c;
for (r = 0; r < howOften; r++) {
row = table.insertRow(-1);
for (c = 0; c < numDays; c++) {
col = row.insertCell(-1);
col.appendChild(document.createTextNode(taskName));
}
}
document.getElementById('holdTable').appendChild(table);
};

Categories