How do I get the cell value from a table using JavaScript? - javascript

<td> <input type="button" name="buton" id="x2" value="2" onclick="swap(id)";/> </td>
This is the button in a table when it is clicked it's id is passed as parameter to function "swap" as below:
function swap(x)
{
document.write(x);
}
It is successful in getting the id but not the value;when i am trying in this way:
function swap(x)
{
document.write(x.value);
}
The output is shown as undefined. Can you tell me how to get the cell value using the cell id?

I believe that what you are looking for is document.getElementById(x).value;
Also if you want the button just pass this to the function like this:
<button onclick="foo(this)"/>

I guess use jQuery for the purpose,it allows to traverse in DOM very easily.
<table id="mytable">
<tr><th>Customer Id</th><th>Result</th></tr>
<tr><td>123</td><td></td></tr>
<tr><td>456</td><td></td></tr>
<tr><td>789</td><td></td></tr>
</table>
If you can, it might be worth using a class attribute on the TD containing the customer ID so you can write:
$('#mytable tr').each(function() {
var customerId = $(this).find(".customerIDCell").html();
}
Essentially this is the same as the other solutions (possibly because I copypasted), but has the advantage that you won't need to change the structure of your code if you move around the columns, or even put the customer ID into a < span >, provided you keep the class attribute with it.
By the way, I think you could do it in one selector:
$('#mytable .customerIDCell').each(function()
{
alert($(this).html());
});
If that makes things easier
Code will be more or less more reliable on cross bowser issue

z = document.getElementById(id); first, and then you should be able to use z.firstChild.textContent

You need to get the cell using var cell = document.getElementById(x). Then use cell.firstChild.nodeValue.
function swap(x)
{
var cell = document.getElementById(x);
document.write(cell.firstChild.nodeValue);
}
EDIT: Tested this on both FF3.5 and IE8 and it works.

If you are passing the id of the element you might want to use document.getElementById(x) to access it.

Related

How can I select the Nth PreviousSibling in Javascript?

In Google Tag Manager it's quite easy to use the element, element classes, element parent classes to fire tags. Unfortunately in this case I want to scrape an element which is only available in the same .
So, when people click on the link "delete" (class=deleteItem) I want to scrape the url_product_id (in bold).
I've tried so much but can't figure out how to achieve this. I hope somebody can help me out.
<td align="center">
<span class="selquantity menosdis"></span>
<span class="selquantity plus"></span>
<input class="urlProductId" type="hidden" name="url_product_id" value="113293">
<input class="urlQuantity" type="text" name="url_quantity" value="1" readonly="readonly">
<br>
<a style="cursor: pointer" class="deleteItem">delete</a>
</td>
Assuming you are wanting to accomplish this within an event handler, you could use parentNode and querySelector to accomplish your goal:
var myClickHandler = function(event) {
var productId = event.target.parentNode.querySelector('. urlProductId').value;
// do stuff with productId
}
Or with jQuery:
$('.deleteItem').on('click', function() {
var productId = $(this).prev('.urlProductId').val();
});
This is similar to Rob's answer, but also takes into account if code is moved around into additional divs, etc.. Since people update their UI all the time. This should be more sustainable as the product matures. Of course you'll want to watch the .closest() call if you ever change to something like BootStrap data tables.
$(".deleteItem").on("click", function() {
var getClosestProdID = $(event.target).closest('td').find('.urlProductId');
// Just for display of the value
alert("Our closest selected value is: " + getClosestProdID.val());
});
JS Fiddle
Here is a jQuery method (modify and test on your own), and you could do this in a GTM Custom Javascript variable:
function(){
var ce = {{Click Element}}; // get the clicked element
if ($(ce).length > 0){
return $(ce).closest('td').find('.urlProductId').attr('name');
}
return undefined;
}
The premise here being that your elements are all nested under the <td> element, and all you're doing is taking the clicked element and scraping for the element you're interested in.

Get td value from specific tr (with mouse hover)

My problem is js sortable table that I also using mouse hover for it.
The problem is when I resort my table the hover url is not updating and I looking for how I can get for specific tr I selected the value of first td.
I tried with different variations such as:
$this.find('td:eq(0)')
or with
getElementById("trselect")
nothing works.
I use it with both mouse hover and probably looking for something like:
document.location.href = "details/" + $('tr').find('td:first-child').text();
Pure JavaScript Solution
There are a bunch of jQuery answers but no jQuery tag so I'm offering a pure JavaScript solution for you. Installing a large library for this simple task seems pointless.
You can assign the row to a Javascript variable like this, and look for mouseover.
To get the first TD's content, you can use a function like this:
function getFirstTdContent(row) {
elem = row.children[0];
alert(elem.textContent); // Do whatever you want to do with the content here
}
To call it, declare your row like this:
<tr onmouseover='getFirstTdContent(this);'>
<td>This should be returned</td>
<td>This should not be returned</td>
</tr>
Try something like this with jQuery:
Add jQuery library:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
Add jQuery code to get value of first TD:
<script>
$(document).ready(function(){
$('tr').mouseover(function(){
var valueOfTd = $(this).find('td:first-child').text();
alert(valueOfTd); // Do here what you want with the value.
document.location.href = 'http://www.google.com/'+ valueOfTd;
});
});
</script>
Looks like you're using jQuery...
Try this:
http://jsfiddle.net/cF63Q/
$(function(){
$('#myTable tr').hover(function(){
console.log($(this).find('td').first().html());
});
});

How to change the value of id or name?

Example:
<table id ='table'>
<tr>
<td>1</td>
<td><select id='old' name='old'></select></td>
<td><select id='old2' name='old2'></select></td>
<td><div id='old3' name='old3'></div></td>
</tr>
</table>
How to change the value of id or name from select id ='old' to select id ='new' (for example) after deleting rows in javascript?
I have been trying all the methods like trying getElementById('old') = 'new' but not work, used replaceChild also not work (or maybe I put the wrong code, no idea).
Do you have other alternatives? (No JQuery, please).
Thanks.
You can use the setAttribute method to accomplish this
document.getElementById("old").setAttribute("id","new");
document.getElementById("new").setAttribute("name","new");
var sel = document.getElementById("old"); //Reference the element
sel.id = "new"; //set the id
try this :
document.getElementById("old").name = 'NewName';
alert(document.getElementById("old").name);
document.getElementById("old").id = 'Newid';
alert(document.getElementById("Newid").id);
its work for me.
I feel there is something inelegant going on here; if you told us more we'd be able to say the "right way" to do it. If you nevertheless have a very good reason to do what you're doing, merely call this snippet of code you have made all your changes. It will update all the elements in your rows to have the correct numbering.
var formElements = document.getElementById('table').getElementsByClassName('toUpdate');
for (var i=0; i<formElements.length; i++) {
var e = formElements[i];
e.id = 'new'+i;
}
There are quite a few variations on this if you didn't want to add a class="toUpdate ..." to each one. For example you were using regular form elements, you could iterate over the <form>'s elements. Or you could iterate through all the elements and pattern-match on the names or ids. Or if you are algorithmically generating this with javascript you could add each element to an array at the same time you add it to the DOM, for later use (like this update).

Optimizing jquery selector for Chrome

I have the following jquery code to loop over 525 (I know, alot!) checkboxes:
var elements = $("#profile-list table tr input[type=checkbox].email-checkout:not(:checked)");
$.each(elements, function(i) {
$(elements[i]).attr('checked', 'checked');
});
UPDATE The html looks like this:
<table>
<tr>
<th>Name</th>
<th>Title</th>
<th>E-mail</th>
<th>Telephone</th>
<th id="email_check"><img src="check_black.png"/></th>
</tr>
<?php foreach ($this->profiles as $profile): ?>
<tr>
<?php echo $this->presentProfile($profile, 'list') ?>
</tr>
<?php endforeach; ?>
This basically loops over all profiles in the database and creates a table row for each profile, where the last table data includes a checkbox, which one can select to send email to. If the user clicks the table header with the id of "email_check" then the javascript code should kick in, and that's where Chrome fails.
I attach the event with the following code:
$("#email_check img").live('click', function() {
//my code
}
When I run this code in Firefox (mac), it goes smoothly but when I run it in Chrome (mac) it takes forever and ends up giving me the window where chrome offers me the option of killing the window, so basically it never completes this loop.
I've been trying to optimize this selector as much as I can, and since jquery 1.3, I understand that they switched from left to right to right to left selector, which basically means that I should try to make my right most selector as specific as I can. Can it be any more specific than I currently have?
Or is it the loop that just takes so long? I have tried switching from $.each to just a regular for() without a positive result.
Any tips or ideas how I can fix this?
Ingiber
I really don't think this is a selector issue at all.
Your selector is a valid selector for querySelectorAll, which means it will be extremely fast.
I tested the exact selector in Chrome on Mac against a table with 250 rows, and the result was instantaneous.
I'd guess that there's something else going on.
Try removing the table tr part of the selector. It isn't adding anything.
Try this:
// console.time("test");
var elements = $("#profile-list input[type=checkbox].email-checkout").get();
var len = elements.length;
for (var i = 0; i < len; i += 1) {
elements[i].checked = true;
}
// console.timeEnd("test");
(So, first we select all check-boxes that are of the class "email-checkout" and are inside the #profile-list element. Then we just set their checked property to true. I assume, this is as fast as it can be.)
You could always give each check box a select/deselect event that will add/remove a class from the checkbox, then use the class as the selector.
You can use a .each() on the set to use the elements directly, like this:
$("#profile-list table tr input[type=checkbox].email-checkout").each(function() {
this.checked = true;
});
Also note the removal of :not(:checked) above...if you're going to check them all, that selector is more expensive that actually checking them anyway. More importantly is that this.checked = true; is tremendously cheaper than $(elements[i]).attr('checked', 'checked'); which happens every time.
Did you profile this? What is taking too long, getting the elements or looping over them? The only way to really speed up code is to profile and fix the slow parts.
FWIW, I would try
var elements = $("#profile-list").find("input[type=checkbox].email-checkout").get();
...
and see what happens.
Add an onlclick on the checkbox
$("#profile-list input[type=checkbox].email-checkout").click(function() {
var obj = $(this);
obj.hasClass("checked") ? obj.removeClass("checked") : obj.addClass("checked");
});
s = $("input[type=checkbox].email-checkout.checked");

How to select a tag with a variable value in jQuery

I am very new to jquery/javscript.
I have a simple question.
Lets say i have a tag like this:
<Table id="mytable" >
<Table>
And i want to add some rows to this table.
Then we do like:
$("#mytable").append("<tr><td>value</td></tr>");
//some thing like this may not be having the right syntax
Now my question is lets the id of the table is in a variable for example:
var table="mytable"; //which is coming from the back end
Now my using the "table" variable how can I append the row..?
Is that going to be
$("#"+table).append("<tr><td>value</td></tr>");//
Can some one help me out in this simple thing?
Thanks,
Swati
that's correct!
var tableId = 'myTable';
$('#' + tableId).append('your row');
will append whatever you put in the 'your row' to the table with the id 'myTable'
That's exactly how you would do it. The selector is only expecting a string, so any form of concatenation or string logic via ternary operators will do the trick. This is a very powerful feature of jQuery selectors.
Yes, you can reference an ID like that by storing a variable in advance. This would append table rows/cells. You may need to dig deeper between the rows and cells depending on what you need to do though. :)
$(document).ready(function () {
var table = "myTable";
$("#" + table).append("<tr><td>row1</td><tr>");
});

Categories