For each element in class, console.log its value - javascript

For each element with the class the_name, I want to alert the value inside that element. So for the code below, it should alert three times. Once each for: "apples", "pears", and "plums".
Not sure what I am missing here.
var arr = $('.the_name');
for(var i = 0; i < arr.length; i++){
alert(arr[i].val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table id="datatable">
<thead>
<tr>
<th></th>
<th>Fruits</th>
</tr>
</thead>
<tbody>
<tr>
<td class="the_name">Apples</td>
<td class="the_count">3</td>
</tr>
<tr>
<td class="the_name">Pears</td>
<td class="the_count">2</td>
</tr>
<tr>
<td class="the_name">Plums</td>
<td class="the_count">5</td>
</tr>
<tr>
<td>Bananas</td>
<td>1</td>
</tr>
<tr>
<td>Oranges</td>
<td>2</td>
</tr>
</tbody>
</table>

By accessing the jQuery object by index you're retrieving the underlying DOMElement, not the jQuery object, and they do not have a val() method. Also note that you seems to be looking to retrieve the text of the element, not the value. As such, you should use each() to loop over the selected elements, using this to refer to the element of the current iteration. Try this:
$('.the_name').each(function() {
alert($(this).text());
});
Also note that for debugging purposes, console.log() should be used instead of alert().
$('.the_name').each(function() {
alert($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table id="datatable">
<thead>
<tr>
<th></th>
<th>Fruits</th>
</tr>
</thead>
<tbody>
<tr>
<td class="the_name">Apples</td>
<td class="the_count">3</td>
</tr>
<tr>
<td class="the_name">Pears</td>
<td class="the_count">2</td>
</tr>
<tr>
<td class="the_name">Plums</td>
<td class="the_count">5</td>
</tr>
<tr>
<td>Bananas</td>
<td>1</td>
</tr>
<tr>
<td>Oranges</td>
<td>2</td>
</tr>
</tbody>
</table>

you need to use .text() instead of .val().
.val() works on input elements (or any element with a value attribute?) and .text() will not work on input elements. .val() gets the value of the input element -- regardless of type. .text() gets the innerText (not HTML) of all the matched elements:
.text()
The result is a string that contains
the combined text contents of all
matched elements. This method works on
both HTML and XML documents. Cannot be
used on input elements. For input
field text use the val attribute.
.val()
Get the content of the value attribute
of the first matched element
you need to use use $ to use jquery method .text().
var arr = $('.the_name');
for(var i = 0; i < arr.length; i++){
alert($(arr[i]).text());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table id="datatable">
<thead>
<tr>
<th></th>
<th>Fruits</th>
</tr>
</thead>
<tbody>
<tr>
<td class="the_name">Apples</td>
<td class="the_count">3</td>
</tr>
<tr>
<td class="the_name">Pears</td>
<td class="the_count">2</td>
</tr>
<tr>
<td class="the_name">Plums</td>
<td class="the_count">5</td>
</tr>
<tr>
<td>Bananas</td>
<td>1</td>
</tr>
<tr>
<td>Oranges</td>
<td>2</td>
</tr>
</tbody>
</table>

The indexed values of a jQuery object are HTML elements, not jQuery objects.
You have to wrap them in a jQuery object before you can call jQuery methods on them:
var arr = $('.the_name');
for(var i = 0; i < arr.length; i++){
var html_element = arr[i];
var $html_element = $(html_element);
alert($html_element.val());
}

Related

How to modify a HTML <td> (without any unique properties) element using Javascript

I'm trying to modify a element using JS however this element does not have any unique properties like ID. Also the table in which this element resides does not have a unique class. Also, the HTML page has multiple tables and td elements.
For example:
Existing HTML :
<table border="1">
<tbody>
<tr>
<td>Id</td>
<td>Name</td>
</tr>
<tr>
<td>12334567</td>
<td>BirthName</td>
</tr>
</tbody>
</table>
I'm trying to modify the cell which contains the value "BirthName" to "BirthName (Sidharth)"
Something Like this:
<table border="1">
<tbody>
<tr>
<td>Id</td>
<td>Name</td>
</tr>
<tr>
<td>12334567</td>
<td>BirthName (Sidharth)</td>
</tr>
</tbody>
</table>
You can find all having BirthName by using bellow colde
const allTds = document.querySelectorAll('td')
// Find the td element that contains the text "BirthName"
const birthDateTd = Array.from(allTds).filter(td=>td.textContent==='BirthName')
After that you can target that <td> as you want.
You can do checking the text for all td and change where matches birthname
let element = document.querySelectorAll('td');
for(let i = 0; i<element.length; i++){
if(element[i].innerText == 'BirthName'){
element[i].innerText += '(Sidharth)';
}
}
If the text is unique then you can use Xpath as shown below and change it.
var td = document.evaluate("//td[contains(text(), 'BirthName')]", document, null, XPathResult.ANY_TYPE, null );
var thisTd = td.iterateNext();
thisTd.innerHTML = "BirthName (Sidharth)";
<table border="1">
<tbody>
<tr>
<td>Id</td>
<td>Name</td>
</tr>
<tr>
<td>12334567</td>
<td>BirthName</td>
</tr>
</tbody>
</table>

Show value in textarea if checkbox is true

I have a table with four columns Name, Age, Country and a checkbox. If the checkbox is clicked(true) the name value of the row is showed in a textarea.
I am not really sure how I can realise that.
A row:
<tr>
<th scope="row">1</th>
<td>James</td>
<td>13</td>
<td>France</td>
<td><input type="checkbox"></td>
</tr>
if the checkbox is true the value "James" should be shown in a textarea.
Thank you all.
I believe you need to do this for multiple rows in a table.
First select all the checkboxes with Document.querySelectorAll() to attach the event (click) to all the checkboxes.
The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
Inside the event (click) handler function target all the checked checkboxes to loop through them to get the relevant names using Array.prototype.map():
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
Also it is not good practice to mix up th and td inside of the same tr element. You should place th inside of a thead and td inside of tbody element:
var cb = document.querySelectorAll('input[type=checkbox]');
cb.forEach(function(ck){
ck.addEventListener('click', function(el){
var checked = document.querySelectorAll(':checked');
var tArea = document.getElementById('myText');
tArea.value = Array.from(checked).map(c => c.closest('tr').querySelector('td:nth-child(2)').textContent);
//or using spread syntax
//tArea.value = [...checked].map(c => c.closest('tr').querySelector('td:nth-child(2)').textContent);
});
});
table, th, td {
border: 1px solid black;
}
<table>
<thead>
<tr>
<th>Sl</th>
<th>Name</th>
<th>No</th>
<th>Country</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td scope="row">1</td>
<td>James</td>
<td>13</td>
<td>France</td>
<td><input type="checkbox"></td>
</tr>
<tr>
<td scope="row">2</td>
<td>John</td>
<td>15</td>
<td>Germany</td>
<td><input type="checkbox"></td>
</tr>
</tbody>
</table>
<textarea id="myText"></textarea>
Try this:
[...document.querySelectorAll("input[type='checkbox']")].forEach(function (v){
v.addEventListener("change", function(){
document.querySelector("textarea").value = (this).checked ? (this).parentElement.parentElement.querySelector("td").innerHTML:'';
})});
<table>
<tr>
<th scope="row">1</th>
<td>James</td>
<td>13</td>
<td>France</td>
<td><input type="checkbox"></td>
</tr>
<tr>
<th scope="row">1</th>
<td>James</td>
<td>13</td>
<td>France</td>
<td><input type="checkbox"></td>
</tr>
</table>
<textarea></textarea>
Few javascript lines would be ok for you need.
let input = document.querySelector('input');
input.addEventListener('change', e=> {
if(e.target.checked == true){
// retreive tags
let name = document.querySelector('.name');
let textarea = document.querySelector('.textarea');
// insert data
textarea.innerText += name.innerText
}
})
<table>
<tr>
<th scope="row">1</th>
<td class="name">James</td>
<td>13</td>
<td>France</td>
<td><input type="checkbox"></td>
</tr>
</table>
<textarea class="textarea"></textarea>
Since your table can have multiple rows, where each can have the checkbox set or not, the textarea could get zero, one or more names.
So you would need to listen the change event, and then iterate the rows to collect the names, to finally set the value of the textarea:
let textarea = document.querySelector("textarea");
let table = document.querySelector("table");
table.addEventListener("change", function (e) {
let names = [];
for (let row of table.rows) {
if (row.querySelector("input[type=checkbox]").checked) {
names.push( row.children[1].textContent);
}
}
textarea.value = names.join("\n");
});
<table><tr>
<th scope="row">1</th>
<td>James</td>
<td>13</td>
<td>France</td>
<td><input type="checkbox"></td>
</tr><tr>
<th scope="row">2</th>
<td>Lucy</td>
<td>14</td>
<td>Germany</td>
<td><input type="checkbox"></td>
</tr></table>
<textarea></textarea>

Delete tabel row with pure javascript

I Need to delete a table row with pure javascript. The table has only a class name, no id.
Here is a fiddle with my first try:
var table = document.getElementsByClassName('table');
while(table.rows.length > 0) {
table.deleteRow(1);
}
https://jsfiddle.net/5s0w6cwL/
Thanks for any advice.
You have to get first element.
var table = document.getElementsByClassName('table')[0];
because document.getElementsByClassName method returns a NodeList.
var table = document.getElementsByClassName('table')[0];
table.deleteRow(1);
<table class="table" border="1">
<tbody>
<tr>
<td> </td>
</tr>
<tr>
<td>delete me</td>
</tr>
<tr>
<td> </td>
</tr>
</tbody>
</table>

jQuery load template inside a loop

I have a json file with some data and I am using a Js loop to load a jQuery template to iterate through and load a table made of 4 rows based on the data, so far I only get the last row. https://github.com/codepb/jquery-template
<script type="text/html" id="tableContent">
<tr>
<th>Key</th>
<th>Product</th>
<th>Bookings</th>
<th>%</th>
<th>Transactions</th>
</tr>
<tr>
<td data-content="">sth</td>
<td data-content="Product"></td>
<td data-content="Bookings"></td>
<td data-content="Percentage"></td>
<td data-content="Transactions"></td>
</tr>
</script>
function builTable(){
var table = "",
colors = ['col1', 'col2', 'col3', 'col4', 'col5', 'col6'];
for(i = 0; i< source.Products.length; i++){
$("table").loadTemplate($("#tableContent"),
{
Product: source.Products[i].Product,
Bookings: source.Products[i].Bookings,
Percentage: source.Products[i].Percentage,
Transaction: source.Products[i].Transaction
} );
$(document).ready(function(){
builTable();
});
<table border="1" cellpadding="2">
</table>
Is there something wrong inside the loop?
http://jsfiddle.net/9JV7t/1/
I think you just need to add an array because it loads the whole content just once and then overrides it again. But therefore you need to only include the data rows in the template and add the headings to the table (DEMO):
<script type="text/html" id="tableContent">
<tr>
<td data-content="">sth</td>
<td data-content="Product"></td>
<td data-content="Bookings"></td>
<td data-content="Percentage"></td>
<td data-content="Transactions"></td>
</tr>
</script>
Your table:
<table>
<thead>
<tr>
<th>Key</th>
<th>Product</th>
<th>Bookings</th>
<th>%</th>
<th>Transactions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
And the js:
function builTable(){
$("tbody").loadTemplate($("#tableContent"), source.Products);
}

How can I get all <tr>-s from a <tbody> and convert it to String?

I have a HTML Table:
<table id="persons" border="1">
<thead id="theadID">
<tr>
<th>Name</th>
<th>sex</th>
<th>Message</th>
</tr>
</thead>
<tbody id="tbodyID">
<tr>
<td>Viktor</td>
<td>Male</td>
<td>etc</td>
</tr>
<tr>
<td>Melissa</td>
<td>Female</td>
<td>etc</td>
</tr>
<tr>
<td>Joe</td>
<td>Male</td>
<td>etc</td>
</tr>
</tbody>
</table>
<input type="button" onclick="getTbodyString();" value="get it"/>
I want some jquery/javascript, which can get the inside of the tbody by String. Like:
function getTbodyString() {
var tbodyString = $(.......).text(); //or val()?
alert("the body - "+tbodyString);
}
The result in the alert window should be this:
the body - <tr><td>Viktor</td><td>Male</td><td>etc</td></tr><tr><td>Melissa</td><td>Female</td><td>etc</td></tr><tr><td>Joe</td><td>Male</td><td>etc</td></tr>
Could anyone help me?
You need to html() instead of text(). The function text will not return you tags but returns plain text within tags.
var tbodyString = $('#tbodyID').html();
I would use native javascript function here that would be faster then jquery.
var tbodyString = document.getElementById('tbodyID').innerHTML; 
Just Replace your function code as below :
function getTbodyString() {
var tbodyString = $('#tbodyID').html();
alert("the body - "+tbodyString);
}

Categories