0

I'm stuck with my small jQuery script. I want to make checkboxes for the rows of a specific table. This would be a greasemonkey script, so I can't edit the source of the site.

This is how the HTML is set up:

<html>
  <head></head>
  <body>
     <table class = test1></table>
     <table class = test2></table>
     <table class = goal>
       <thead>
         some some <tr> 
       </thead>
       <tbody>
         here are the table rows where I want to put the checkboxes
       </tbody>
     </table>
  </body>
</html>

The problem is that, is puts checkboxes in the rows at every "tr" what it can find in all the tables. And finally my code:

var $ = unsafeWindow.jQuery

$(document).ready(function (){
  $("table.goal").ready(function(){
    $("tbody").ready(function(){
      $("tr").prepend('<td><input type="checkbox" name="x" value="y"></td>');
    });
  });
}); 

Please, someone would be so kind to explain me, why this isn't working as intended? Thanks in advance.

5 Answers 5

1

There is no need to use table.ready/tbody.ready, you have to use descendant-selector

$(document).ready(function () {
    $("table.goal tbody tr").prepend('<td><input type="checkbox" name="x" value="y"></td>');
});

Demo: Fiddle

Note: If the rows are created dynamically, then the dom manipulation need to be executed after the tr's are created

Sign up to request clarification or add additional context in comments.

Comments

0

Try this,

$(document).ready(function (){
    $("table.goal tbody tr").each(function(){
       //check if a checkbox is already added or not
       if($(this).find('td:eq(0) > input[type="checkbox"]').length)
       {
          $(this).prepend('<td><input type="checkbox" name="x" value="y"></td>');
       }
    })
}); 

Comments

0

try

$("tbody tr").prepend('<td><input type="checkbox" name="x" value="y"></td>');

It should omit the thead.

Comments

0
Hope this might help you... :)  

    $(.goal tr).prepend('<td><input type="checkbox" name="x" value="y"></td>');

Comments

0
function AddCheckboxToTable($table) {
    var $thead = $table.find('> thead');
    var $tbody = $table.find('> tbody');

    $thead.find('> tr').prepend('<th>Checkbox</th>');
    $tbody.find('> tr').each(function(index, element) {
        var $tr = $(element);
        $tr.prepend('<td><input type="checkbox" name="checkbox" value="'+index+'">   </td>');
    });
};

$(function() {
    AddCheckboxToTable($('table.goal'));
});

See this fiddle : http://jsfiddle.net/dYAkJ/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.