开发者

Looping through html table with jQuery

I have a html table and I want 开发者_StackOverflowto basically loop through each row and each cell per row and simply print out the results. The one thing is some of the cells have input boxes, some have select dropdowns and some have raw content inside the TD.

What is the fastest way to simply looop through every cell in an html table and get the result of each cell. for the select dropdowns I would want to capture the value of the select (not the display text).


Online demo: http://jsbin.com/ewazu

I'm cycling through each TD first and evaluating whether or the the first-child is an input element. If it is, we return its value. If it's not, we ask if it produces text. If it produces text, we ask for the text. If it doesn't produce text, we request the HTML for the TD:

$("table td").each(function(i,o){
  var value = ( $(":first-child", this).is(":input") ) 
    ? $(":first-child", this).val() 
    : ( $(this).text() != "" ) 
      ? $(this).text() 
      : $(this).html() ;
  alert(value);
});


It's hard to know exactly what you want, but if you can assume that td's with a select box have only that, td's with an input have only a text field, you could do something like this: http://jsbin.com/alara3/edit


Since there's going to be only one element inside each cell, you could do something like:

$("#myTable tr").each(function() {
    // this represents the row
    $("td > *", this).each(function() {
        // nodeName attribute represents the tag - "INPUT" if element is <input>
        // use the type attribute to find out exactly what type 
        // of input element it is - text, password, button, submit, etc..
        if(this.nodeName == "INPUT") {
            console.log($(this).attr("type"));
        }
    });
});

#myTable > tr means get all <tr> elements that are children of some id="myTable".

Likewise, td > * means get all children of the <td> element that's represented by the this object right now. These are all CSS selectors and there are various ways to select an item in the DOM. See the jQuery docs to learn more about selectors.

The jQuery core docs are a great reference to find out about all available methods on the jQuery object.


you can use following code.

$(':input', '#tableId').val('');
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜