Input field not appending to td - javascript

I am trying to create a table with an input field dynamically but my code ends up creating an empty table.
var calcDiv = document.getElementById("calc_div");
var calcTab = document.createElement('TABLE');
var tbody = document.createElement('TBODY');
var calcForm = document.createElement('FORM');
calcForm.id = "calculator_form";
//calc display
var tr = document.createElement('TR');
var td = document.createElement('TD');
td.colspan = "4";
var comp = document.createElement('INPUT');
comp.type = "text";
comp.value = 0;
comp.disabled = true;
comp.id = "compDisplay";
td.appendChild(comp); //THIS DOESN'T SEEM TO WORK
tr.appendChild(td);
tbody.appendChild(tr);
calcForm.appendChild(comp);
calcTab.appendChild(tbody);
calcTab.style.width = "500px";
calcTab.style.height = "500px";
calcDiv.appendChild(calcTab);

You were missing a line and were incorrectly appending another. In:
tr.appendChild(td);
tbody.appendChild(tr);
calcForm.appendChild(comp);
You needed to:
tr.appendChild(td);
tbody.appendChild(tr);
calcTab.appendChild(tbody); <-- append the tbody to the table
calcForm.appendChild(calcTab); <-- append the table to the form
jsFiddle example
This produces the HTML:
<div id="calc_div">
<table style="width: 500px; height: 500px;">
<tbody>
<tr>
<td>
<input type="text" disabled="" id="compDisplay">
</td>
</tr>
</tbody>
</table>
</div>
Note that you may also want to use td.setAttribute('colspan','4'); instead of td.colspan = "4";

Maybe because you are adding the input named "comp" again in the form after two rows? "calcField.addChild(comp)"

What's happening is you're appending comp to the td, then appending it to the form after that. This removes it from the table it was in and puts it in the form, which isn't attached anywhere in your document.
Here's a sample with the appending to the form commented out. Or perhaps you'd prefer to append the form to the td instead.

I think this method will help you out. I've coded it so that the appendChild follows the DOM tree. Take a look. Note: I created a variable to append the target "calc_div" to the document body. Feel free to take that out.
var div = document.body.appendChild(document.createElement('div'));
div.id = "calc_div";
var table = div.appendChild(document.createElement('table'));
table.style.width = "500px";
table.style.height = "500px";
var tbody = table.appendChild(document.createElement('tbody'));
var trow = tbody.appendChild(document.createElement('tr'));
var tcell = trow.appendChild(document.createElement('td'));
tcell.colSpan = "4";
var input = tcell.appendChild(document.createElement('input'));
input.id = "compDisplay";
input.type = "text";
input.value = 0;
input.disabled = true;

Related

To do list javascript-something is wrong with my code/order

I'm building a small to do list and everything worked fine so far until I included a checkbox. now when I click on the button, nothing happens and neither do I see a checkbox. There must be something wrong with the order of code-does someone know how I need to rearrange the code and WHY?
Html code:
<body>
<h1>To Do List</h1>
<p><input type="text" id="textItem"/><button id="add">Add</button></p>
<ul id="todoList">
</ul>
</body>
Javascript code:
function addItem() {
var entry = document.createElement("li");
var checkBox = document.getElementById("input");
checkBox.type = "checkbox";
var span = document.createElement("span");
span.innerText = entry;
var textItem = document.getElementById("textItem");
entry.innerText = textItem.value;
var location = document.getElementById("todoList");
entry.appendChild(checkBox);
entry.appendChild(span);
location.appendChild(entry);
}
var item = document.getElementById("add");
item.onclick = addItem;
UPDATED - I've spotted 4 issues . Follow Below :
1st : When you create the check box you should be using setAttribute method to specify input type : checkbox.setAttribute("type" , "checkbox")
2nd : Your checkbox variable should be creating an input element : var checkBox = document.createElement("input");
3rd : You should be using innerHtml instead of innerText as you are referencing a list ELEMENT stored in your entry variable : span.innerHtml = entry;
4th: Really minor but you should grab your item and attach an event to the item before your function :
var item = document.getElementById("add");
item.addEventListener("click" , addItem)
Just change your javascript to the following :
var item = document.getElementById("add");
item.addEventListener("click" , addItem)
function addItem() {
var entry = document.createElement("li");
var checkBox = document.createElement("input");
checkBox.setAttribute("type" , "checkbox");
var span = document.createElement("span");
span.innerHtml = entry;
var textItem = document.getElementById("textItem");
entry.innerText = textItem.value;
var location = document.getElementById("todoList");
entry.appendChild(checkBox);
entry.appendChild(span);
location.appendChild(entry);
}
Example Here : http://codepen.io/theConstructor/pen/pyPdgg
Good Luck!

Add JQuery functionality to dynamically created radio buttons

I'm currently trying to add a jQuery function to a row of radio buttons. The problem is that I need to add dynamically many rows. Now For this example I only added 2 elements into the array of newNodes, but in my application newNodes can potentially have many different sizes.
So basically I want to add the Query function something like this:
$('#rowID input').on('change', function() {
alert($('input[name=i]:checked', '#rowID').val());
});
Where it exists inside the forloop and is added for each new row. "rowID" is a variable assigned to the unique row identifier and then use the loop iterator "i" as a way to distinguish the radio buttons for each row.
Here is the HTML:
<form id="createEdges" method="POST>
<fieldset>
<legend class="title">Modify the graph!</legend>
<table id="createEdgesTable">
</table>
<input type="button" class="btn btn-default" id="backToThirdForm" onclick="goBackToForm3()" value="Back"/>
</fieldset>
And Here is the Javascript:
newNodes = [];
newNodes.push(0);
newNodes.push(1);
//get HTML Table to add rows in
var edgeTable = document.getElementById("createEdgesTable");
//Create a table row for each node
for (var i in newNodes) {
var row = edgeTable.insertRow();
row.id = "node" + i;
//Show name of the node
var td = document.createElement('td');
var text = document.createTextNode(newNodes[i]);
td.appendChild(text);
row.appendChild(td);
//Choice for showing node
var td2 = document.createElement('td');
var radioButton1 = document.createElement('input');
radioButton1.type = "radio";
radioButton1.name = i;
radioButton1.value = "showNode";
td2.appendChild(radioButton1);
row.appendChild(td2);
//Choice for creating edge
var td3 = document.createElement('td');
var radioButton2 = document.createElement('input');
radioButton2.type = "radio";
radioButton2.name = i;
radioButton2.value = "createEdge";
td3.appendChild(radioButton2);
row.appendChild(td3);
//Choice for deleting node
var td4 = document.createElement('td');
var radioButton3 = document.createElement('input');
radioButton3.type = "radio";
radioButton3.name = i;
radioButton3.value = "removeNode";
td4.appendChild(radioButton3);
row.appendChild(td4);
var rowID = row.id;
}
$('#node0 input').on('change', function() {
alert($('input[name=0]:checked', '#node0').val());
});
JSFiddle: https://jsfiddle.net/nxexrq9y/
Any example on how to make this work for each row? I'm relatively new to JQuery and have been stuck on this problem for quite some time now. Thank you for your time and help!
Just change your script with following code.
$('tr[id^=node] input').on('change', function() {
alert(this.value);
});
Explanation:
Scripts find any tr whose id starts with node. this covers all your dynamically generated TRs. Further selection narrows down to only input element in each TR, and registers change event for that element. On that change event your have already got that element so you can easily access its value there.
Here is Js Fiddle Link
Further if you want to know clicked radio falls in which node, you can check out this js fiddle.
$('tr[id^=node] input').on('change', function() {
var row = $(this).parents('tr:first').get(0);
alert('Node: '+ row.id+ ' value:' + this.value);
});

JS - Getting input from a form & putting it into array and then appending a new row to table (DOM)

I'm trying to get input from a form and putting it into an array and then putting that array into a new row to a table using DOM manipulation. I have this so far and while it is receiving the value I put in, the value is not displayed in the table but a blank row is inserted. Please help!
(function(){
var theValue;
var formControls = document.getElementById('theForm');
var table = document.querySelector('info');
var handler = function (){
var tbody = document.getElementsByTagName('tbody').item(0);
for (var i = 0; i < 3; i++) {
var tr = 'tr' + [i],
tr = document.createElement('tr');
var displayValue = 'td' + [i],
displayValue = document.createElement('td');
var enteredValue = this['present-value'].value;
theValue = document.createTextNode(enteredValue);
tr.appendChild(displayValue);
tbody.appendChild(tr);
return false;
}
} // end handler
formControls.onsubmit = handler;
})();
HTML
<div id="container">
<div id="controls">
<h2>Controls</h2>
<form id="theForm">
<fieldset>
<label for="present-value">Enter Value</label>
<input id="present-value" name="present-value" type="text">
<button type="submit">Add</button>
</fieldset>
</form>
</div>
<div id="display">
<h2>Values</h2>
<table class="info">
<thead>
<tr>
<th>Value</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
You might look at JQuery's .serializeArray() method:
http://api.jquery.com/serializeArray/
Just some comments:
> var table = document.querySelector('info');
That attempts to get an element with a tag name of "info". There is no such element in HTML.
> var tr = 'tr' + [i],
> tr = document.createElement('tr');
That will overwrite the previous value of tr
> var displayValue = 'td' + [i],
> displayValue = document.createElement('td');
and that will overwrite the previous value of td.
> var enteredValue = this['present-value'].value;
I presume that this is a reference to the form. Does it have a "present-value* attribute or property? This line tries to get the present-value property of the form, then read it's value property. Likely it just throws an error or returns undefined.
Can you post some minimal HTML to go with the code? As far as I can see, the above will not do anything useful.

Add/Remove rows dynamically in a table in javascript

I want to add/remove rows in a table dynamically. I have javascript function to add and remove the rows. But, I want the delete button beside every single row so that I can delete a particular row.
ANd I want to add a row only if the first row is completely filled.
function to remove row
function removeRowFromTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}
function to add rows:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
cell2.appendChild(element2);
}
my table:
<table id="tableId">
<tr><td>Host Name</td><td>Directory</td></tr>
<tr><td><input type="text"/></td><td><input type="text"/></td></tr>
<tr><td><input type="button" value="+" onclick="addRow(tableId)"/></td>
<td><input type="button" value="-" onclick="removeRowFromTable()"/></td></tr>
</table>
Any help is appreciated! Thanks in Advance!!!
If you put a delete button on each row, then:
<tr>
<td><input type="button" value="Delete row" onclick="deleteRow(this)">
<td><input type="text">
<td><input type="text">
</tr>
And the deleteRow function can be:
function deleteRow(el) {
// while there are parents, keep going until reach TR
while (el.parentNode && el.tagName.toLowerCase() != 'tr') {
el = el.parentNode;
}
// If el has a parentNode it must be a TR, so delete it
// Don't delte if only 3 rows left in table
if (el.parentNode && el.parentNode.rows.length > 3) {
el.parentNode.removeChild(el);
}
}
BTW, if all your rows have the same content, it will be much faster to add a row by cloning an existing row:
function addRow(tableID) {
var table = document.getElementById(tableID);
if (!table) return;
var newRow = table.rows[1].cloneNode(true);
// Now get the inputs and modify their names
var inputs = newRow.getElementsByTagName('input');
for (var i=0, iLen=inputs.length; i<iLen; i++) {
// Update inputs[i]
}
// Add the new row to the tBody (required for IE)
var tBody = table.tBodies[0];
tBody.insertBefore(newRow, tBody.lastChild);
}
You can avoid a lot of cross browser headaches by using jquery. Here is a sample.
http://jsfiddle.net/piyushjain7/gKJEs/
Javascript has this really useful function called deleteRow where if you know the index you are deleting from, you can simply input that number, and then it'll delete that specific row (index's starting at 0 - tbl.rows.length).
I also found a nice example that uses it in action. You can adjust it to fit your needs though (although his uses checkboxes which might be a lot cleaner than just making a button next to every single row). I don't encourage you to blatantly copy the code so if there is anything that confuses you, please let us know. Hope this helps.
EDIT: I didn't see you wanted to add rows after you found out the last row was completely filled. I'll update my answer when I figure that out. However, the basic idea of that is to check if the <td> tag has text in it (perhaps check if the text inside the tag isn't a blank or if there is a <td> tag at all and then if it isn't empty, make a new <tr> element else don't.
See http://jsfiddle.net/9gnAx/
HTML & JavaScript (body):
<table id="tableId">
<tr>
<th>Host Name</th>
<th>Directory</th>
<td><input class="add" type="button" value="+" /></td>
</tr>
<tr>
<td></td><td></td>
<td><input class="add" type="button" value="+" /></td>
</tr>
</table>
<script type="text/javascript">
(function(){
var els=getElementsByClassName("add","tableId");
for(var i=0;i<els.length;i++){
els[i].onclick=addRow;
}
els[0].onclick();
})();
</script>
CSS (head):
.add,.del{
width:25px;
}
JavaScript (head):
function getElementsByClassName(c,el){
if(typeof el=='string'){el=document.getElementById(el);}
if(!el){el=document;}
if(el.getElementsByClassName){return el.getElementsByClassName(c);}
var arr=[],
allEls=el.getElementsByTagName('*');
for(var i=0;i<allEls.length;i++){
if(allEls[i].className.split(' ').indexOf(c)>-1){arr.push(allEls[i])}
}
return arr;
}
function killMe(el){
return el.parentNode.removeChild(el);
}
function getParentByTagName(el,tag){
tag=tag.toLowerCase();
while(el.nodeName.toLowerCase()!=tag){
el=el.parentNode;
}
return el;
}
function delRow(){
killMe(getParentByTagName(this,'tr'));
}
function addRow() {
var table = getParentByTagName(this,'table')
var lastInputs=table.rows.length>2?
table.rows[table.rows.length-2].getElementsByTagName('input'):[];
for(var i=0;i<lastInputs.length-1;i++){
if(lastInputs[i].value==''){return false;}
}
var rowCount = table.rows.length;
var row = table.insertRow(rowCount-1);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "button";
element3.className="del";
element3.value='-';
element3.onclick=delRow;
cell3.appendChild(element3);
}
Update:
RobG has made me realize that getParentByTagName throws an error if there isn't any parent with the nodeName passed.
If you want a more general getParentByTagName, which doesn't throw errors, you can use
function getParentByTagName(el,tag){
tag=tag.toLowerCase();
while(el&&el.nodeName.toLowerCase()!=tag){
el=el.parentNode;
}
return el||null;
}
And when you call the function you should check if the result is null.
Updated jsfiddle: http://jsfiddle.net/9gnAx/1/

Getting HTML table data (td) (i.e. text or val) using table header (th) into Textarea

I have SQLite3 (i.e. Spatialite query) that outputs the results into HTML table. I want to get the AsText(Geometry) data to output in <textarea>
Here is the table and some assumptions.
<table>
<tr>
<th>name</th>
<th>AsText(Geometry))</th>
</tr>
<tr>
<td>Andres Street</td>
<td>LINESTRING(7.120068 43.583917,7.120154 43.583652,7.120385
43.582716,7.12039 43.582568,7.120712 43.581511,7.120873 43.580718)</td>
</tr>
</table>
$('#wktInput').click(function(){
???
???
var asTextGeometryText =
$("#wktResult").text(asTextGeometryText);
});
<textarea name='wktResult' value ='wktResult' ROWS="10" COLS="50" >'Should Display AsText(Geometry Column here!'</textarea>
This is the DOM
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var fieldNames = aResult.fieldNames;
var records = aResult.data;
var numFields = fieldNames.length;
var numRecords = records.length;
var container = document.getElementById('queryResults');
container.innerHTML = '';
var table = document.createElement('table');
container.appendChild(table);
var headerRow = document.createElement('tr');
table.appendChild(headerRow);
for(var i = 0; i < numFields; i++){
var header = document.createElement('th');
header.innerText = fieldNames[i];
headerRow.appendChild(header);
}
for(var i = 0; i < numRecords; i++){
var tableRow = document.createElement('tr');
table.appendChild(tableRow);
for(var j = 0; j < numFields; j++){
var tableData = document.createElement('td');
tableRow.appendChild(tableData);
tableData.innerText = records[i][j];
}
}
}
<input id='SQLinput' size="90" rows="3" value = 'SELECT name, AsText(Geometry) FROM Roads Where MbrContains(Geometry, MakePoint(7.120872,43.580722,4326))'></input>
<input type='button' class='button' value='Display AsText' ontouchend='wktAsTextInput'/>
Thanks in advance
It seems that texarea uses id for value.
<textarea id="field1">example text</textarea>
[This problem is related to textarea in jQuery as well][1]
This example below demonstrate that jquery is not working in textarea using id.
<script type="text/javascript">
$(function() {
$('button').click(function() {
var row = $('input:first').val();
var column = $('input:eq(1)').val();
var cell = $('table tr:eq('+row+') td:eq('+column+')');
if (cell.length == 0) {
$('#value').text('Undefined');
}
else {
$('#value').text(cell.text());
}
});
});
</script>
</head>
<body>
<h1>Table Cell Value</h1>
<table>
<tr><td>Cell 1-1</td><td>Cell 1-2</td><td>Cell 1-3</td></tr>
<tr><td>Cell 2-1</td><td>Cell 2-2</td><td>Cell 2-3</td></tr>
<tr><td>Cell 3-1</td><td>Cell 3-2</td><td>Cell 3-3</td></tr>
</table>
Row: <input type="text" value="0">
Column: <input type="text" value="0">
Value: <span id="value">?</span><br>
Textarea: <textarea id="value" >Try this! this is not working</textarea>
<button>Get Value</button>
All is working in this example. Then added a textarea to see if I can make it work. Textarea is not working in this example. Something wrong with jquery and textarea using id as well as name.
Textarea: <textarea name="value" >Try this! this is not work as well</textarea>
How this does not work.
New info about this textarea value.
$('#id_of_textarea').attr('value'); //to get and...
$('#id_of_textarea').attr('value','updated value of textarea'); //to set it...
<textarea id="editor_desc" onkeyup="update_textarea(this)"></textarea>
function update_textarea(obj)
{
$('#mydiv').text($(obj).attr('value')); //whatever you type in the textarea would be reflected in #mydiv
}
http://blog.ekini.net/2009/02/24/jquery-getting-the-latest-textvalue-inside-a-textarea/
It seems that my problem is not rendering a regular html tablet but a direct render to the screen.
The author of QuickConnect say told me,
If you want one of those values so that you can use it you need to pull it
out of the 2D array.
Do you mean displaying the content in AsText(Geometry) column at the textarea?
var text = []
$('table').find('tr:has(td)').each(function(){
text.push($.trim($(this).find('td:eq(1)').html()));
})
// and you set it to your textarea
$('textarea[name="wktResult"]').val(text.join('\n'));
1- assign an id attribute to your textarea to use it in jquery or if your page contain just one textarea you can use tag name insteasd.
2- to get text of textarea you need just call text function without any parameters
$('#wktInput').click(function(){
var asTextGeometryText =$('table').find('th').eq(2).text();
$('#id_of_textarea').attr('value',asTextGeometryText);
});

Categories