My goal is to go through a table and append a new <tr> with the same data as it's previous sibling but with some altered content text.
A section of my html is as follows:
<tr>
<td><label>Share - Spanish</label></td>
<td><input type="text" id="blog_share_es" name="blog_share_es" size="30" /></td>
</tr>
Within my current function in Javascript the $(this) is the <label> tag. I have successfully taken the word "Spanish" and replaced it with "Italian" with the following:
var italian = $(this).text().replace("Spanish", "Italian");
and then append it to the table as follows:
var parentDiv = $(this).parent().parent();
$('<tr><td><label>'+italian+'</label></td><td><input type="text" id="logout_de" name="logout_de" size="30"/></td></tr>').insertAfter(parentDiv);
How do I now select the <input> and replace all instances of "_es" within the id and name with "_it" so that I get the following output in html (getting the formatting of the html is not necessary but would be optimal!):
<tr>
<td><label>Share - Italian</label></td>
<td><input type="text" id="blog_share_it" name="blog_share_it" size="30" /></td>
</tr>
Turned into a plug-in
DEMO
(function ($) {
$.fn.newRow = function (language, suffix) {
$lastSibling = this.find("tr").last().clone();
$label = $lastSibling.find("label");
$labelText = $label.text();
$label.text($labelText.replace($labelText.substring($labelText.indexOf("- ") + 2), language));
$input = $lastSibling.find("input");
$id = $input.attr("id");
$name = $input.attr("name");
$input.attr("id", $id.replace($id.substring($id.lastIndexOf("_") + 1), suffix))
.attr("name", $name.replace($name.substring($name.lastIndexOf("_") + 1), suffix));
this.find("tbody").append($lastSibling);
return this;
};
})(jQuery);
$("#yourTable").newRow("Italian", "it");
something like this... not sure if it 100% works, but gives you right direction
$('input[type=text]').each(function(input) {
if (input.attr('id').match(/_it/))
input.attr('id', input.attr('id').replace(/_it/, '_es');
if (input.attr('name').match(/_it/))
input.attr('name', input.attr('name').replace(/_it/, '_es');
})
To select the input starting from $(this) you have to use the function find(), and then you can change the attributes using the function attr()
var inp = $(this).parent().parent().find("input[type=text]");
inp.attr("id", inp.attr("id").replace("_es","_it"));
inp.attr("name", inp.attr("name").replace("_es","_it"));
Related
I have some code :
<table>
<tbody>
<tr>
<td id='myTdId'>
<input type='text' value='some value' />
</td>
</tr>
...
</tbody>
<table>
I want to get innerHTML of myTdId td element and get value of text input. Is it possible?
for example :
var tdInnerHTML = document.getElementById('myTdId').innerHTML;
// convert this to element operation and access to value of it ...
console.log(tdInnerHTML.value); // :(
please help me, THANKS...
EDIT :
I do not access to input text!
How about using childNodes to navigate?
It is an array containing nodes of contained elements.
In your case...
var tdInputVal = document.getElementById('myTdId').childNodes[0].value;
console.log(tdInputVal ); // :(
Can you add Id on the input itself?
<table>
<tbody>
<tr>
<td id='myTdId'>
<input type='text' value='some value' id="myInput" />
</td>
</tr>
...
</tbody>
<table>
Then access it via
var input = document.getElementById('myInput').value;
Or access it via tag
var input = document.getElementsByTagName("input")[0].value;
Alternative clear way is to have id or class on your HTML so you can get inner value easily.
For example
HTML:
<input id="text-input" value="">
Javascript
var inputValue = document.getElementById('text-input').value;
console.log(inputValue);
jQuery version
var inputValue = $('#text-input').val();
Hope this helps.
I dont think you need to call innerHTML on that element. You need to get child of the td element with id "myTdId". To do that you can use
var tdElement = document.getElementById('myTdId');
console.log(tdElement.children[0].value);
This should get you the value of the td Element without the need of setting id or class to the td element.
I am assuming you have only one element inside the td;
I did not test the code but it should work.
Use getElementById than use on result object also getElementBy_XXX .
If you use getElementsByClassName or TagName you will get array of child element.
//ELEMENT
var tdElement = document.getElementById('myTdId');
// INNER HTML
var tdInnerHTML = document.getElementById('myTdId').innerHTML;
var childElement = tdElement.getElementsByTagName("input");
//if td is only and always first element than we can use :
//childElement[0]
alert(childElement[0].value)
<table>
<tbody>
<tr>
<td id='myTdId'>
<input type='text' value='some value' />
</td>
</tr>
</tbody>
<table>
<script>
// I dont use this function but you can if you want
function getElementInsideElement(baseElement, wantedElementID) {
var elementToReturn;
for (var i = 0; i < baseElement.childNodes.length; i++) {
elementToReturn = baseElement.childNodes[i];
if (elementToReturn.id == wantedElementID) {
return elementToReturn;
} else {
return getElementInsideElement(elementToReturn, wantedElementID);
}
}
}
</script>
// Use querySelector
var input = document.querySelector('#myTdId input');
var val = input.value;
I have made this table: https://jsfiddle.net/Hougaard114/7qy70wpo/
It looks like i want it to, but it doesn't work quite like i want to. At the moment every input field has its own name, and therefor its own variable in JavaScript.
What i want is to have a Javascript function with a minimal amount of variable. What happens in each row is the same. The last row "u-værdi" spits out the result of 1/sum of"isolans"s. So i thought i could make a javascript looking like this:
function isolansBeregn () {
var calc1 = document.getElementById('lambda').value;
var calc2 = document.getElementById('tykkelse').value;
var result = calc2/calc1;
var numb = result;
numb = numb.toFixed(0);
document.getElementById('isolans').innerHTML = numb;
var uVærdi = 1/result;
uVærdi = uVærdi.toFixed(3);
document.getElementById('uværdi').innerHTML = uVærdi;}
It works, but only for the first row of inputs. Even though i give the next row the same id's, nothing happens when i type in numbers.... So now it looks like this:
HTML
<table>
<thead>
<th colspan="4">Demo</th>
</thead>
<tbody>
<tr>
<td style="width: 30%" class="tdh">Materiale</td>
<td style="width: 30%"class="tdh">Lambda værdi (λ<sub>50</sub>)</td>
<td style="width: 30%"class="tdh">Tykkelse (m)</td>
<td style="width: 10%"class="tdh">Isolans</td>
</tr>
<tr>
<td>Yderbeklædning</td>
<td><input type="number" id="lambda" placeholder="Skriv her" onchange="isolansBeregn()"></td>
<td><input type="number" id="tykkelse" placeholder="Skriv her" onchange="isolansBeregn()"></td>
<td id="isolans"></td>
</tr>
<tr>
<td>Isolering</td>
<td><input type="number" id="lambda2" placeholder="Skriv her" onchange="isolansBeregn()"></td>
<td><input type="number" id="tykkelse2" placeholder="Skriv her" onchange="isolansBeregn()"></td>
<td id="isolans2"></td>
</tr>
<tr>
<td>Inderbeklædning</td>
<td><input type="number" id="lambda3" placeholder="Skriv her" onchange="isolansBeregn()"></td>
<td><input type="number" id="tykkelse3" placeholder="Skriv her" onchange="isolansBeregn()"></td>
<td id="isolans3"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3">U-værdi</td>
<td id="uværdi"></td>
</tr>
</tfoot>
</table>
and JavaScript
function isolansBeregn () {
var calc1 = document.getElementById('lambda').value;
var calc2 = document.getElementById('tykkelse').value;
var calc3 = document.getElementById('lambda2').value;
var calc4 = document.getElementById('tykkelse2').value;
var calc5 = document.getElementById('lambda3').value;
var calc6 = document.getElementById('tykkelse3').value;
var result = calc2/calc1;
var result2 = calc4/calc3;
var result3 = calc6/calc5;
var numb = result;
numb = numb.toFixed(0);
var numb2 = result2;
numb2 = numb2.toFixed(0);
var numb3 = result3;
numb3 = numb3.toFixed(0);
document.getElementById('isolans').innerHTML = numb;
document.getElementById('isolans2').innerHTML = numb2;
document.getElementById('isolans3').innerHTML = numb3;
var uVærdi = 1/((result+result2)+result3);
uVærdi = uVærdi.toFixed(3);
document.getElementById('uværdi').innerHTML = uVærdi;}
It feels like overkill.
The reason this is a problem for me, is because i want the user to be able to add another row, looking exactly like the others, with a JavaScript that doesn't mind.
Thank you in advance!
The minimal modifications version is:
Change the ids to names (except for uværdi)
Change your
onchange="isolansBeregn()"
to
onchange="isolansBeregn(this)"
so it passes a reference to the element on where the change occurred into the function.
Then we can work from that element what row we're in, and therefore find the other input elements in that row:
function isolansBeregn(input) {
// Update this row
var row = $(input).closest("tr");
var calc1 = row.find('[name=lambda]').val(); // Probably worth converting these to number explicitly
var calc2 = row.find('[name=tykkelse]').val();
var result = Math.round(calc2 / calc1); // Added rounding at the number rather than text level
row.find('[name=isolans]').html(result).data("result", result); // ** see below
// Get the sum of all the results
var sum = $("[name=isolans"]).get().reduce(function(s, el) {
return s + $(el).data("result");
}, 0);
var uVærdi = 1 / sum;
uVærdi = uVærdi.toFixed(3);
$('#uværd').html(uVærdi); // Again, perhaps .text()
}
Re my ** see below: We're displaying the number as text, but we'll need it as a number later, so we use jQuery's data feature to store it as a number as well. We could use the text are reparse it as a number, but I went the other way.
Explanation of reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Note: I used jQuery because you tagged jquery, but your code doesn't seem to be using jQuery anywhere. The above is totally possible without jQuery as well. The only bit that's really any more work is the .closest part.
However, this is a good use case for event delegation. You can get rid of all of those onchange=... attributes, and instead hook change on the table, and then use e.target to know which actual input changed. (The change event doesn't bubble natively, but jQuery makes it bubble, so event delegation works with it.)
I am trying to create a row of text boxes dynamically through Javascript and read the values of the textbox in JSON. Later,I have to read JSON and display the values in textarea and this should achieved only though jquery and javascript.
I am able to create the text boxes dynamically but I am unable to read the values in JSON. When I use the jQuery part(mentioned below),the javascript to dynamically create textboxes is not working.Any suggestions please.
<table id="myTable">
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Occupation and Employer</th>
<th>Add</th>
<tr>
<td><input type="text" id="txtName" /></td>
<td><input type="text" id="txtAge" /></td>
<td><input type="text" id="txtGender" /></td>
<td><input type="text" id="txtOccupation" /></td>
<td><input type="button" id="btnAdd" class="button-add" onClick="insertRow()" value="add"></input></td>
<td><input type="button" id="btnSave" class="button-add" value="Save"></input> </td>
</tr>
</table>
<script>
var index = 1;
function insertRow()
{
var table=document.getElementById("myTable");
var row=table.insertRow(table.rows.length);
var cell1=row.insertCell(0);
var t1=document.createElement("input");
t1.id = "txtName"+index;
cell1.appendChild(t1);
var cell2=row.insertCell(1);
var t2=document.createElement("input");
t2.id = "txtAge"+index;
cell2.appendChild(t2);
var cell3=row.insertCell(2);
var t3=document.createElement("input");
t3.id = "txtGender"+index;
cell3.appendChild(t3);
var cell4=row.insertCell(3);
var t4=document.createElement("input");
t4.id = "txtOccupation"+index;
cell4.appendChild(t4);
index++;
}
$(document).ready(function(){
$("#btnsave").click(function ()
{
alert("Hi");
var dataToSend={
'Name':[],
'Age':[]};
dataToSend.Name.push({$("txtName").val().trim()});
dataToSend.Age.push({$("txtAge").val().trim()});
localStorage.setItem('DataToSend', JSON.stringify(DataToSend));
var restoredSession = JSON.parse(localStorage.getItem('dataToSend'));
// Now restoredSession variable contains the object that was saved
// in localStorage
console.log(restoredSession);
alert(restoredSession);
});
});
JSFIddle:http://jsfiddle.net/S7c88/
Since you are using jQuery you can greatly simplify the whole process by using methods like clone().
Here's a working example where I created one array of row objects. Since you aren't doing this in a form, I removed the ID's and just used data-name.
var $row;
function insertRow() {
$('#myTable').append($row.clone());
}
$(function () {
$row = $('tr').eq(1).clone(); /* clone first row for re-use*/
$('#myTable').on('click', '.btnSave', function () {
var dataToSend = [];
$('tr:gt(0)').each(function () {
var data = {};
$(this).find('input').each(function () {
data[$(this).data('name')] = this.value
});
dataToSend.push(data);
});
/* display data in textarea*/
$('#output').val(JSON.stringify(dataToSend, null, '\t'))
});
}) ;
I changed your input type=button to button to take advantage of using input selector while looping rows to create data and not have to filter out the buttons
Your demo has invalid html, missing <tr> for top set of <th>
DEMO
Some areas where you were going wrong:
$("txtName") Invalid selector
No row references in attempt to gather data
This is my first attempt in Javascript, so may be this is fairly easy question.
I need to access row element of a table, each row contains checkbox and two other column. If checkbox is checked, i need to get the id of checkbox.
I made following attempt but element_table.rows returns undefined, therefore i could not proceed. I debugged using Inspect element tool of eclipse and found element_table contains the rows.
Please suggest where I am making a mistake.
Javascript code:
function myfunction3(){
var element_table = document.getElementsByName('collection');
var element_tableRows = element_table.rows;
var selectedTr = new Array();
var data = "";
for(var i =0 ; element_tableRows.length;i++)
{
var checkerbox = element_tableRows[i].getElementsByName('checkmark');
if(checkerbox.checked){
selectedTr[selectedTr.length] = element_tableRows[i].getAttribute("name");
data = data + element_tableRows[i].getAttribute("name");
}
}
var element_paragraph = document.getElementsByName('description');
element_paragraph.innerHTML = data;
}
html code:
<table name="collection" border="1px">
<tr name="1">
<td><input type="checkbox" name="checkmark"></td>
<td>Tum hi ho</td>
<td>Arjit singh</td>
</tr>
<tr name="2">
<td><input type="checkbox" name="checkmark"></td>
<td>Manjha</td>
<td>Somesh</td>
</tr>
<tr name="3">
<td><input type="checkbox" name="checkmark"></td>
<td>Ranjhana</td>
<td>A.R Rehman</td>
</tr>
</table>
<input type="button" value="Check" onclick="myfunction3()">
here's a working version
function myfunction3(){
var element_table = document.getElementsByName('collection');
var element_tableRows = element_table[0].rows;
var selectedTr = new Array();
var data = "";
for(var i =0 ; i < element_tableRows.length;i++)
{
var checkerbox = element_tableRows[i].cells[0].firstChild;
if(checkerbox.checked){
//selectedTr[selectedTr.length] = element_tableRows[i].getAttribute("name"); //not sure what you want with this
data = data + element_tableRows[i].getAttribute("name");
}
}
var element_paragraph = document.getElementsByName('description');
element_paragraph.innerHTML = data;
alert(data);
}
http://jsfiddle.net/eZmwy/
jsfiddle for your example, your problem is mainly at when you getElementsByName you need to specify the index, also not that not all getElement methods are available in the table
i would also suggest you learn jQuery, this makes life easier, also not sure why you want to display the data as 1,2,3 the name on the tr... seems pretty strange to me
Actually this line
var element_table = document.getElementsByName('collection');
will return collection of elements. If you are sure that you have exactly one table with the specified name, try this approach:
var element_table = document.getElementsByName('collection')[0];
actually if you are using jQuery (very recommanded )
you can do something like
var idsArray = [];
$("[name=collection] tr td [type=checkbox]:checked").parent().each(function() {
idsArray .push($(this).attr('name'))
});
this answer related only to jQuery use (which is same as javascript only more compiled.)
Hello I have a piece of code that allows me to add an author.
I have a problem, I can't seem to delete the created node in my table
This is the worst frustration in my life. I could not seem to delete it.
I also have notice that every time I inspected the element I could not see the
new created element from the source. But when I view it on firebug I can actually see it there.
Adding an input element and appending it on the table works fine for me.
I am just very new to JavaScript and to this web thingy and deleting a CREATED ELEMENT via .createElement is where I am stuck at.
here is my code
<script>
var ctr = 1;
function showTextBox()
{
// is the table row I wanted to add the element before
var target = document.getElementById('bef');
var tblr = document.createElement('tr');
var tbld1 = document.createElement('td');
var tbld2 = document.createElement('td');
var tblin = document.createElement('input');
tblin.name = 'Author' + ctr;
tblin.id = 'Author' + ctr;
tblin.placeholder = 'add another author';
tbld1.appendChild( document.createTextNode('Author' + ctr ) );
tbld2.appendChild( tblin );
tblr.appendChild( tbld1 );
tblr.appendChild( tbld2 );
target.parentNode.insertBefore( tblr , target );
ctr++;
}
function hideTextBox()
{
var name = 'Author'+ctr;
var pTarget = document.getElementById('tbhold');
var cTarget = document.getElementById( name );
alert( cTarget ); // this one return null? Why? I have created id="Author1"
// viewing this code on source make the created elem to not appear
}
</script>
Am I doing something wrong? I really need help. This is for my project at school.
Is there any way I could delete it. I created that node and I want it to be deleted when I click something.
Also I prefer to stay with JS not with JQuery or other JStuff and I am disregarding compatibility for now because this is just a sample in my dummy form. I will deal on that later.
EDIT
In case you need the actual form here it is
<form enctype="multipart/form-data" action="process/" method="POST" />
<h3>Book Upload</h3>
<table border="2" id='tbhold'>
<tr>
<td>Title</td>
<td><input type="text" id="book_title" name="book_title" /></td>
</tr>
<tr>
<td>Author</td>
<td><input type="text" id="book_author" name="book_author" /></td>
</tr>
<tr id="bef">
<td colspan="2">
add author
remove
</td>
</tr>
</table>
</form>
Thank you very much!
Try this function:
function removeElements(elements){
for(var i = 0; i < elements.length; i++){
elements[i].parentNode.removeChild(elements[i]);
}
}
Then you can do this:
removeElements(document.querySelectorAll('#tbhold tr'));
function hideTextBox(){
var name = "Author" + (ctr - 1);
var pTarget = document.getElementById('tbhold');
var cTarget = document.getElementById(name);
var tr = cTarget.parentNode.parentNode;
tr.parentNode.removeChild(tr);
ctr = ctr - 1;
}
Here is a demo
every time I inspected the element I could not see the new created element from the source. But when I view it on firebug I can actually see it there.
If you change the DOM, you of course do not change the HTML source markup. Only the DOM inspector will show you the changes.
var name = 'Author'+ctr;
var cTarget = document.getElementById( name );
alert( cTarget ); // this one return null? Why? I have created id="Author1"
Yes, you created it using your showTextBox function. But that did also increment the ctr to 2, so that you now are looking for Author2 which obviously does not exist. So put a ctr--; before it and it should work.