Creating a New jQuery Plugin

<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>

When repeating each element, trcheck if this element is installed <tr>if it adds a new class. If not, delete 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 tested one tr:

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

Unfortunately, this does not work for me. I will be grateful for any help.

+3
source share
3 answers

Instead, checkboxyou need it :checkboxfor the selector, since there are no elements <checkbox>, for example:

$(':checkbox',this)

Although you can shorten the general approach with .toggleClass("className", bool)for example:

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

Also, there is no need for .each()calling your plugin, only this will do:

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

You can test all changes above here .

+4

: $('checkbox',this)

, , , checkbox, , .

[type=checkbox] :checkbox ( )

, :

if ($('[type=checkbox]',this).is(':checked'))

:

if ($(':checkbox',this).is(':checked'))

. JQuery.

, .

+1

You do not need a plugin for this:

$('.data tbody tr:has(:checkbox:checked)').addClass("delemarked");
$('.data tbody tr:has(:checkbox:not(:checked))').removeClass("delemarked");

or (depending on your taste)

$('.data tbody tr:has(:checkbox)').removeClass("delemarked").has(':checkbox:checked').addClass('delemarked');
+1
source

Source: https://habr.com/ru/post/1767856/


All Articles