Skip to content Skip to sidebar Skip to footer

Accessing The Contents Of A Table Cell In Javascript

I've got a checkbox nested inside a table cell element in HTML. How can I access the inner checkbox from Javascript? All of the examples I've seen alter the inner HTML itself, or t

Solution 1:

If you are not using jQuery then you could do:

document.getElementsByTagName('input');

And then cycling through them to find one that is checkbox and parentNode is table cell.

Or very simply add ID to that checkbox.

Solution 2:

if you are using jquery its very simple;

$('table td input:checkbox')

UPDATE

without jquery.

<table id='table'>
  ...
  <td><input name='input'type='checkbox' /></td>

</table>


var table = document.getElementById('table');

var inputs = table.getElementsByTagName('input')

var chkbox = [];

for (var i=0; i< inputs.length;i++) {
   if (inputs[i].type == 'checkbox') {
      chkbox.push(inputs[i]);
   }

}

now all your check boxes are inside chkbox array

if you want to access from a form its also easy:

var ckbox = document.formname.checkboxname;

Solution 3:

You can use an id...

Demo: http://jsfiddle.net/YTDeW/1/

document.getElementById('ck1').value;

...

<table><tr><td>checkbox 1<inputtype="checkbox"id="ck1"name="ck"value="check1" /></td><td>checkbox 2<inputtype="checkbox"id="ck2"name="ck"value="check2" /></td><td>checkbox 3<inputtype="checkbox"id="ck3"name="ck"value="check3" /></td></tr></table>

...

or you can get all that have the same name attribute...

var y = document.getElementsByName('ck');
for (var i = 0; i < y.length; i++) {
    document.getElementById('trace').innerHTML += "<br />" + y[i].value;
}

Solution 4:

If your input is in a form, then you can ignore the table completely for access purposes:

<form name="aForm" ...>
  // Whatever table structure you like<inputname="anInput"...></form>

You can access the input as:

var inp = document.aForm.anInput;

or more formally as:

var inp = document.forms['aForm'].elements['anInput'];

noting that if you have more than one form control in that form with the name anInput, inp will be a collection of those elements.

Post a Comment for "Accessing The Contents Of A Table Cell In Javascript"