I have a table in HTML:
<tr class="inner2-top">
<td class="name1"> Hello </td>
</tr>
How would I get the name1 in a javascript variable function like this?
function grabData() {
var name = // todo
}
You want the data that's inside of the td?
function grabData(className) {
return document.getElementsByClassName(className)[0].innerText;
}
console.log(grabData("name1"));
I suggest using id attributes instead of class attributes if you're going to use this method, though. ids are unique whereas classes are not, which will explain why you get unexpected results if you have more than one element with the class "name1" etc.
var name = $(".name1").text();
Try the above
you can get that text using class selector
var getName=$('.name1').html();
alert(getName);
DEMO
Related
I have this code which show me the list of my item
<tbody class="table-color2">
<c:forEach var="defect" items="${defectList}">
<tr>
<td id="defectId"><a onclick="getDefectId()">${defect.id}</a></td>
<td>${defect.createdDate}</td>
<td>${defect.reportedBy.firstName}</td>
<td>${defect.title}</td>
<td>${defect.bugtype.description}</td>
<td>${defect.status.description}</td>
<td>${defect.priority.description}</td>
</tr>
</c:forEach>
</tbody>
what Im trying to do is to get the value of the td id="defectId" when it is clicked, my jquery script for the onclick is this :
function getDefectId(){
var defectId = $(' #defectId ').val();
alert("Defect ID " + defectId);
}
but currently, I'm getting a value of undefined, how do I get the value?
You have several issues. Firstly you're appending the same id in a loop, which will result in duplicates which is invalid. Also, a elements don't have a value to retrieve so you need to use text(). Finally note that using your current method would mean that you need to pass the this reference of the clicked element to the function.
However you can tidy all that up by using classes and hooking up the event in JS. Try this:
<tbody class="table-color2">
<c:forEach var="defect" items="${defectList}">
<tr>
<td class="defect">${defect.id}</td>
<td>${defect.createdDate}</td>
<td>${defect.reportedBy.firstName}</td>
<td>${defect.title}</td>
<td>${defect.bugtype.description}</td>
<td>${defect.status.description}</td>
<td>${defect.priority.description}</td>
</tr>
</c:forEach>
</tbody>
$(function() {
$('.defect a').click(function(e) {
e.preventDefault();
console.log($(this).text());
});
});
Working example
You can do the following(remember that id needs to be unique):
<td class="defectId"><a onclick="getDefectId(${defect.id})">${defect.id}</a></td>
And in you function:
function getDefectId(value){
alert("Defect ID " + value);
}
Try this : use text() instead of val() because you want to know the text inside td and not the value of input element.
EDIT: - Sorry, missed that there are multiple td's. In this case, you must not use same id for all tds. Just make it class and do following changes in function.
function getDefectId(){
var defectId = $('.defectId').text();
alert("Defect ID" + defectId);
}
I would suggest to use jQuery event handler instead of calling javascript function. See below code
HTML: remove onclick call
<td class="defectId">${defect.id}</td>
jQuery : register a click handler and read text
$(function(){
$('.defectId a').click(function(){
var defectId = $(this).text();
alert(defectId);
});
});
The following code outputs a table with values, and according to the value, it gets a layout. I use jQuery (Ajax) to update the information every 10 seconds.
php script that generates the wanted variables and stores (echoes) them into a json array (example.php)
$variable1 = 20;
if ($variable1 > 0) {
$td_variable1class="positive";
} else {
$td_variable1class="negative";
}
$array['variable1'] = $variable1;
$array['td_variable1'] = $td_variable1;
echo json_encode($array);
html table where the variable is retrieved from the json generated by the example.php:
<table>
<tr>
<td class='variable1class'>
<div id='variable1'></div>
</td>
</tr>
</table>
javascript:
<script type="text/javascript">
$(function() {
refresh();
});
function refresh() {
$.getJSON('example.php', function(data) {
$('div#variable1').html(data.variable1);
$('td.td_variable1').addClass(data.td_variable1);
});
setTimeout("refresh()",10000);
}
The problem is the "addClass" adds a class to the existing class, resulting in an output like this:
before the refresh:
<td class="td_variable1 positive">
after (assuming the variable changed from positive to negative):
<td class="td_variable1 positive negative">
I tried to avoid this by using removeclass:
$('td.td_variable1').removeClass().addClass(data.td_variable1);
But then the actual class name of the td is removed and my output looks like this:
<td class="negative">
and it should look like this:
<td class="td_variable1 negative">
Thanks for your help in advance!
Assuming you only have those 2 options, remove both (and only those two) then add the new one:
$('td.td_variable1').removeClass("positive negative").addClass(data.td_variable1);
.removeClass() removes all classes when not given any parameter. Use .removeClass("negative") instead.
What i'm trying to do is to get the cell of this where the classname is "revision_id".
<tr>
<td class="supplierOrderId">10790</td>
<td class="revision_id">#7</td>
<td class="supplier">DGI Developpement </td>
<td class="quantity">80</td>
<td class="stock">0</td>
<td class="purchase_price">10.00</td>
<td class="comments"> </td>
</tr>
I managed to do it this way :
revision = this.parentNode.parentNode;
revisionId = revision.cells[1].innerHTML.replace( /[^\d.]/g, '' );
(cause I wanna get the int of the string)
iRevisionId = parseInt(revisionId);
Is there a more proper way to do it, with the given className ?
Because in the case where someone adds a cell before mine in the future, my code is going to be "deprecated".
Hope i've given all the details,
Thanks by advance.
// More Details //
The problem with most answers is that they work only if I have 1 <tr>. Once I get multiple, it gets every revisionID like this :
console.log(result) -> #1#2#3#4
(if I have 4 <tr> for exemple)
So this is why I am getting the GOOD one like this :
revision = this.parentNode.parentNode; // outputs the good <tr>
but after that, I can't get the with the given className.
if this is tr
var data = $(this).children(".revision_id").text()
Using the text() method, you can get the text inside your td element.
After that just parse it like you did with parseInt()
$(function() {
var quantity = $('tr td.quantity').text();
console.log(parseInt(quantity));
});
you can do via jquery like this:
var value= parseInt($(".vision_id").text().match(/[0-9]+/g)[0]);
FIDDLE EXAMPLE
Depends on whether you can use jQuery or not.
Pure JavaScript
With pure JS, provided you're using a modern browser, you can use the getElementsByClassName function. For the purpose of this demonstration, I've assumed you have an ID on your table you can use.
var myClassName = 'revision_id';
var table = document.getElementById('mytable');
// the desired TD
var td = table.getElementsByClassName( myClassName ) );
See Mozilla's docs on getElementsByClassName.
Also, this answer works with backwards compatibility.
jQuery
Of course, this becomes easier with jQuery:
var $td = $('#mytable td.revision_id');
Demo here: http://jsfiddle.net/uJB2y/1/
Well if you want it with jquery then you can use .filter() method:
var text = $('td').filter(function () {
return this.className === 'revision_id';
}).text().slice(1);
text = +text; // conversion for int
alert(text);
Demo
I'm using a css class to define grouping in table rows:
<table>
<tr class="otherClasses group1">...</tr>
<tr class="otherClasses group1">...</tr>
<tr class="otherClasses group2">...</tr>
<tr class="otherClasses group2">...</tr>
...
<tr class="otherClasses groupN">...</tr>
</table>
Now I need to loop through all the rows in my table and get groupX for each one. Then I'll split the string and extract group ID.
What's the correct/best way to get groupX class among all tr classes only giving group prefix?
You should be able to use attribute contains selector in jQuery:
$('tr[class*="group"]')
Have a look at jquery selectors documentation for more info. You may need to tweak the value depending on your specifics (e.g. add a space before group).
The following will return an array with "group" classes:
var groupClasses = $(".otherClasses").map(function() {
return (this.className.match(/group\d+/) || []).pop();
}).get();
Or in each() iteration:
$(".otherClasses").each(function() {
var groupClass = (this.className.match(/group\d+/) || []).pop();
// ...
});
How can I use jQuery to get a particular instance of a class(headerGrid) within a Div(products).
I need to be able to get an instance of the class 'headerGrid' classed span which says "Get this Text". The instance is represented as the value within swap2(). My code is as follows...
<table id="products">
...
<tr>
<td>
<a onclick="swap2(1);"><img src="images/products/thumbs/image.png"/></a>
</td>
<td valign="top" class="product-text">
<span class="headerGrid">Get this Text</span><br /><br />
text
</td>
</tr>
...
</table>
E.g. if onclick="swap2(5);" then I need to get the 5th instance of '.headerGrid'
EDIT
Further more I need to select the text("Get this Text") rather then the object itself. Other wise it returns object [object Object].
I also tried selecting with .innerHTML which returns undefined.
Use the eq() selector. Example:
$("#products span.headerGrid").eq(4) //Zero based index
With your function:
function swap2(n) {
//Zero based index, subtract 1
var theText = $("#products span.headerGrid").eq(n - 1).html();
...
}
Using the :nth-child selector:
$('#products span.headerGrid:nth-child(5)')
Use $("#products span.headerGrid:nth-child(5)"), which will return the 5th span with class headerGrid in your element with ID products.
Function swap could look like this:
function swap(n){
var element = $("#products span.headerGrid:nth-child(" + n + ")");
//Rest of code
}
Small notice: You've mentioned DIV(products) in your question, but your code shows table.