I have a HTML table that looks like this:
<tr class="row-class" role="row">
<td>Text1</td>
<td>
<form method='get' action='http://example.php'>
<input type='hidden' name='id_num' value='ABCD123'> <!-- < I NEED THIS VALUE -->
<button type='submit' class='btn' title='Check' ></button>
</form>
</td>
</tr>
I want to get the value of the hidden input type named id_num. (In this example the value I want is "ABCD123").
I tried to parse the code with cheerio like this:
var $ = cheerio.load(body);
$('tr').each(function(i, tr){
var children = $(this).children();
var x = children.eq(0);
var id_num = children.eq(1);
var row = {
"x": x.text().trim(), //this is correct, value is Text1
"id_num": id_num.text().trim() //This is empty, value is "", I want the value "ABCD123"
};
});
But I only get the first value correct.
How can I get the value from the hidden input element id_num?
Thanks.
That should be:
$(tr).find('[name="id_num"]').attr('value')
Your eq(1) was getting the whole <tr>, try this instead:
$('tr').each(function(i, tr){
var children = $(this).children('td');
var x = $(children[0]);
var id_num = $(children[1]).find("input[name='id_num']");
var row = {
"x": x.text(),
"id_num": id_num.val()
};
}
Related
I try to generate a text field in a table:
The table gets bigger with the input of the user that's why I cant just write the
input syntax in the html document, because the cell isnĀ“t generated from the beginning.
function tableAdd() {
var table = document.getElementById("table");
var titel = document.getElementById("Titel").value;
var description = document.getElementById("Description").value;
var row = table.insertRow();
var projectCell=row.insertCell(0);
projectCell.innerHTML = titel;
// down here is the problem
var x =row.insertCell(1);
x.innerHTML = document.createElement("INPUT")
x.innerHTML.setAttribute("type", "text");
}
The problem is that x.innerHTML is a string, not a html element. You need to set attribute on html element, not string. You can do like this:
var x =row.insertCell(1);
var y = document.createElement("INPUT");
y.setAttribute("type", "text");
x.appendChild(y);
You are trying to assign a reference of HTMLInputElement which is returned from the call to document.createElement("input"); to the non-existent innerHTML property of a HTMLTableRowElement (newRow in my example) reference, returned by insertCell(1);.
Instead you can assign any text value to the value attribute of the HTMLInputElement(input variable in my example) and append the dynamic input to the newly created cell.
function tableAdd() {
var table = document.getElementById("table");
var titel = document.getElementById("Titel").value;
var description = document.getElementById("Description").value;
var row = table.insertRow();
var projectCell=row.insertCell(0);
projectCell.innerHTML = titel;
var newRow =row.insertCell(1);
var input = document.createElement("input");
input.type = "text";
input.value= description
newRow.appendChild(input);
}
tableAdd();
<body>
<input type="text" id="Titel" value="test"/>
<input type="text" id="Description" value="test"/>
<table id="table">
</table>
<button onclick="tableAdd()">add</button>
</body>
Here is the reference documentation:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement/insertCell
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement
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;
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.)
Ok so im trying to add two (or more) variables and make it appear in a table cell.
I get the variables from lets say the 1st and 2nd cells and i want to display them on the 7th cell, so this is what i have for now.
This is the basic code for the cell that gets the info.
function prompta1()
{
var a1=prompt("Unesi broj","")
var spana1 = document.getElementById ("spana1");
spana1.innerHTML = a1;
function prompta2()
{
var a2=prompt("Unesi broj","")
var spana2 = document.getElementById ("spana2");
spana2.innerHTML = a2;
And this is the code for the cell that needs to show them.
function functiona7()
{
var a7= spana1+spana2;
var spana7 = document.getElementById ("spana7");
spana7.innerHTML = a7;
}
Now , when i try this it only gives.
[object HTMLSpanElement][object HTMLSpanElement]
Please help!
HTML for getting the values
enter code here <tr>
<td><h1>1</h1></td>
<td><input type="button" onclick="prompta1()" value="Izmeni"> <br> <span id='spana1'></span></td>
<td><input type="button" onclick="prompta2()" value="Izmeni"> <br> <span id='spana2'></span></td>
</tr>
<tr>
HTML for showing the value
<td> <input type="button" onclick="functiona7()" value="Izracunaj"> <br> <span id='spana7'></span> </td>
Try something like this:
function prompta1() {
var a1 = prompt("Unesi broj", "");
var spana1 = document.getElementById("spana1");
spana1.innerHTML = a1;
}
function prompta2() {
var a2 = prompt("Unesi broj", "");
var spana2 = document.getElementById("spana2");
spana2.innerHTML = a2;
}
function functiona7() {
var spana1 = document.getElementById("spana1").innerHTML;
var spana2 = document.getElementById("spana2").innerHTML;
var spana7 = document.getElementById("spana7");
if (!(spana1 && spana2 && spana7)) return;
var a7 = spana1 + spana2;
spana7.innerHTML = a7;
}
Fiddle
In your current example the values for spana1/2 are not pulling from the DOM, so first they need to be populated using getElementById, after that a simple combination of the Inner Html is all that is needed (although you may want to add a space in between too).
I want to get each cell value from an HTML table using JavaScript when pressing submit button.
How to get HTML table cell values?
To get the text from this cell-
<table>
<tr id="somerow">
<td>some text</td>
</tr>
</table>
You can use this -
var Row = document.getElementById("somerow");
var Cells = Row.getElementsByTagName("td");
alert(Cells[0].innerText);
function Vcount() {
var modify = document.getElementById("C_name1").value;
var oTable = document.getElementById('dataTable');
var i;
var rowLength = oTable.rows.length;
for (i = 1; i < rowLength; i++) {
var oCells = oTable.rows.item(i).cells;
if (modify == oCells[0].firstChild.data) {
document.getElementById("Error").innerHTML = " * duplicate value";
return false;
break;
}
}
var table = document.getElementById("someTableID");
var totalRows = document.getElementById("someTableID").rows.length;
var totalCol = 3; // enter the number of columns in the table minus 1 (first column is 0 not 1)
//To display all values
for (var x = 0; x <= totalRows; x++)
{
for (var y = 0; y <= totalCol; y++)
{
alert(table.rows[x].cells[y].innerHTML;
}
}
//To display a single cell value enter in the row number and column number under rows and cells below:
var firstCell = table.rows[0].cells[0].innerHTML;
alert(firstCell);
//Note: if you use <th> this will be row 0, so your data will start at row 1 col 0
You can also use the DOM way to obtain the cell value:
Cells[0].firstChild.data
Read more on that in my post at http://js-code.blogspot.com/2009/03/how-to-change-html-table-cell-value.html
You can get cell value with JS even when click on the cell:
.......................
<head>
<title>Search students by courses/professors</title>
<script type="text/javascript">
function ChangeColor(tableRow, highLight)
{
if (highLight){
tableRow.style.backgroundColor = '00CCCC';
}
else{
tableRow.style.backgroundColor = 'white';
}
}
function DoNav(theUrl)
{
document.location.href = theUrl;
}
</script>
</head>
<body>
<table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">
<% for (Course cs : courses){ %>
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">
<td name = "title" align = "center"><%= cs.getTitle() %></td>
</tr>
<%}%>
........................
</body>
I wrote the HTML table in JSP.
Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title.
courses is an ArrayList of Course objects.
The HTML table displays all the courses titles in each cell. So the table has 1 column only:
Course1
Course2
Course3
......
Taking aside:
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"
This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp . "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.
I told you just in case you'll want to use it because I searched a lot for it and I found questions like mine. But now I found out from teacher so I post where people asked.
The example is working.I've seen.
Just simply.. #sometime when larger table we can't add the id to each tr
<table>
<tr>
<td>some text</td>
<td>something</td>
</tr>
<tr>
<td>Hello</td>
<td>Hel</td>
</tr>
</table>
<script>
var cell = document.getElementsByTagName("td");
var i = 0;
while(cell[i] != undefined){
alert(cell[i].innerHTML); //do some alert for test
i++;
}//end while
</script>
<td class="virtualTd" onclick="putThis(this)">my td value </td>
function putThis(control) {
alert(control.innerText);
}
I found this as an easiest way to add row . The awesome thing about this is that it doesn't change the already present table contents even if it contains input elements .
row = `<tr><td><input type="text"></td></tr>`
$("#table_body tr:last").after(row) ;
Here #table_body is the id of the table body tag .
Here is perhaps the simplest way to obtain the value of a single cell.
document.querySelector("#table").children[0].children[r].children[c].innerText
where r is the row index and c is the column index
Therefore, to obtain all cell data and put it in a multi-dimensional array:
var tableData = [];
Array.from(document.querySelector("#table").children[0].children).forEach(function(tr){tableData.push(Array.from(tr.children).map(cell => cell.innerText))});
var cell = tableData[1][2];//2nd row, 3rd column
To access a specific cell's data in this multi-dimensional array, use the standard syntax: array[rowIndex][columnIndex].
Make a javascript function
function addSampleTextInInputBox(message) {
//set value in input box
document.getElementById('textInput').value = message + "";
//or show an alert
//window.alert(message);
}
Then simply call in your table row button click
<td class="center">
<a class="btn btn-success" onclick="addSampleTextInInputBox('<?php echo $row->message; ?>')" title="Add" data-toggle="tooltip" title="Add">
<span class="fa fa-plus"></span>
</a>
</td>