views:

129

answers:

5
<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?

A: 

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

XKpe
A: 

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

kb
Not in IE (6 and 7, at least). You'd have to use `innerText` there.
Tim Down
+2  A: 

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)"/>
the_drow
A: 

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.

Kaleb Brasee
i think the correct way is cell.firstChild.textContent, atleast in firefox
kb
In all this approach,you are required to keep writing the same code again and again for separate Browsers...So go for jQuery
Sam Rudolph
+1  A: 

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

Sam Rudolph
He is a noob, jQuery isn't the way to go here. He needs to know javascript first.
the_drow
I'd say still go for the jQuery +1
gmcalab
Really? how would he know how it's done in the background? Imagine that he comes to a workplace that doesn't use a js framework...
the_drow
but still jQuery is better framework,than just simple javascript,It solves the cross browsers issues also,without re-writing the code again and again for separate browsers
Sam Rudolph