开发者

Accessing the contents of a table cell in Javascript

I've got a checkbox nested inside a table cell element开发者_StackOverflow中文版 in HTML. How can I access the inner checkbox from Javascript? All of the examples I've seen alter the inner HTML itself, or the visual properties, which is not what I'm interested in. I've tried the childNodes array, but it's empty, apparently.


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.


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;


You can use an id...

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

document.getElementById('ck1').value;

...

<table>
    <tr>
        <td>checkbox 1<input type="checkbox" id="ck1" name="ck" value="check1" /></td>
        <td>checkbox 2<input type="checkbox" id="ck2" name="ck" value="check2" /></td>
        <td>checkbox 3<input type="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;
}


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

  <input name="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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜