Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a new jQuery plugin

Tags:

jquery

<table class="data" border="1">
    <tbody>
        <tr>
        </tr>
            <td><input type="checkbox" /></td>

        <tr>
            <td><input type="checkbox" /></td>

        </tr>
        <tr>
            <td><input type="checkbox" /></td>
        </tr>        
    </tbody>
</table>

While iterating through each tr element, check whether the given <tr> element has a checked checkbox, if so add the new class. If not, remove it.

jQuery.fn.deleteMark = function() {

   this.each(function() {
        alert( $('input:checkbox',this) );
        if ($('checkbox',this).is(':checked')){
            $(this).addClass("delemarked");
        }
        else{
            $(this).removeClass("delemarked");
        }
   })
};

Now I want to add a class to each tr that is checked:

function refresh(){
    $('.data tbody tr').each(function() {
        $(this).deleteMark();
    });        
}

Sadly this doesn't work for me. I will be grateful for any help.

like image 388
Hellnar Avatar asked Feb 13 '26 07:02

Hellnar


1 Answers

Instead of checkbox, you need :checkbox for a selector, as there are no <checkbox> elements, like this:

$(':checkbox',this)

Though you can shorten your overall approach with .toggleClass("className", bool), like this:

jQuery.fn.deleteMark = function() {
  return this.each(function() {
    $(this).toggleClass("delemarked", $(this).find(":checkbox:checked").length > 0);
  });
};

Also, there's no need for the .each() calling your plugin, just this will do:

$('.data tbody tr').deleteMark();

You can test all of the change above here.

like image 165
Nick Craver Avatar answered Feb 15 '26 15:02

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!