admin管理员组

文章数量:1291767

I have three check boxes of types "One", "Two"and "Three" and a table which is having a column as 'Type' that contains three distinct values One, Two and Three across few rows.
My requirement is, based on the check boxes selected or deselected only those rows of the table should be shown for which the value of the 'Type' column match the check box value.

For example,

if check box "One" is selected, those rows having "One" as Type should be shown.
if both "One" and "Three" is selected,those rows having "One" and "Three" as type should be displayed.
again if "Three" is deselected, rows matching "Three" as Type should be hidden,only rows of Type "One" should be shown and so on.

But, I am not able to produce the desired result, attached the code below, can anybody please help.

 <html>

<head>
    <script src =".11.1/jquery.    min.js"></script>
    <title>Hello </title>
</head>

<body>
<table>
    <tr>
        <td>
<input type='checkbox' onclick='return filter_type(this);' name='filter'  id="One"  value= "One" />
                 One
     </td>
    <td>
<input type='checkbox' onclick='return filter_type(this);' name='filter'  id="One"  value= "Two" />
                 Two
    </td>
    <td>
<input type='checkbox' onclick='return filter_type(this);' name='filter'  id="One"  value= "Three" />
                 Three
    </td>
    </tr>
 </table>

 <table class="datatbl"  border=1>
    <tr>
        <th>No.</th>
        <th>Content</th>
        <th>Type</th>
    </tr>
    <tr>
        <td>1</td>
        <td>this is first row</td>
        <td>One</td>
    </tr>
    <tr>
        <td>2</td>
        <td>this is second row</td>
        <td>Two</td>
    </tr>
    <tr>
        <td>3</td>
        <td>this is third row</td>
        <td>Three</td>
    </tr>
    <tr>
        <td>4</td>
        <td>this is fourth row</td>
        <td>One</td>
    </tr>
    <tr>
        <td>5</td>
        <td>this is fifth row</td>
        <td>Two</td>
    </tr>
    <tr>
        <td>6</td>
        <td>this is sixth row</td>
        <td>Three</td>
    </tr>

</table>
<style>
.datatbl {
background-color: palegreen;
}
</style>
<script>
function filter_type(box) {
//alert("checked");
 var cbs = document.getElementsByTagName('input');
 var all_checked_types = [];
 for(var i=0; i < cbs.length; i++) {
     if(cbs[i].type == "checkbox") {
             if(cbs[i].name.match(/^filter/)) {
                     if(cbs[i].checked) {
                         all_checked_types.push(cbs[i].value);
                      }
                  }
           }
  }
 //alert("all checked "+ all_checked_types);
 if (all_checked_types.length > 0) {
     $('.datatbl tr').each(function (i, row) {
         var $tds = $(this).find('td'),
         type = $tds.eq(2).text();
         if (type && all_checked_types.indexOf(type) >= 0) {
             //alert("matched");
             $(this).show();
          }
      });
  }
    else {
        $('.datatbl tr').each(function (i, row) {
            var $tds = $(this).find('td'),
            type = $tds.eq(2).text();
            $(this).show();
         });
    }
    return true;
 }  

</script>

</body>
</html>

function filter_type(box) {
//alert("checked");
 var cbs = document.getElementsByTagName('input');
 var all_checked_types = [];
 for(var i=0; i < cbs.length; i++) {
	 if(cbs[i].type == "checkbox") {
        	 if(cbs[i].name.match(/^filter/)) {
                     if(cbs[i].checked) {
                         all_checked_types.push(cbs[i].value);
                      }
                  }
           }
  }
 //alert("all checked "+ all_checked_types);
 if (all_checked_types.length > 0) {
     $('.datatbl tr').each(function (i, row) {
         var $tds = $(this).find('td'),
         type = $tds.eq(2).text();
         if (type && all_checked_types.indexOf(type) >= 0) {
             //alert("matched");
             $(this).show();
          }
      });
  }
    else {
        $('.datatbl tr').each(function (i, row) {
            var $tds = $(this).find('td'),
            type = $tds.eq(2).text();
            $(this).show();
         });
    }
    return true;
}	
.datatbl {
background-color: palegreen;
}
<html>

<head>
	<script src =".11.1/jquery.	min.js"></script>
	<title>Hello </title>
</head>

<body>
<table>
	<tr>
		<td>
<input type='checkbox' onclick='return filter_type(this);' name='filter'  id="One"  value= "One" />
                 One
	 </td>
	<td>
<input type='checkbox' onclick='return filter_type(this);' name='filter'  id="One"  value= "Two" />
                 Two
	</td>
	<td>
<input type='checkbox' onclick='return filter_type(this);' name='filter'  id="One"  value= "Three" />
                 Three
	</td>
 	</tr>
 </table>

 <table class="datatbl"  border=1>
	<tr>
		<th>No.</th>
		<th>Content</th>
		<th>Type</th>
	</tr>
	<tr>
		<td>1</td>
		<td>this is first row</td>
		<td>One</td>
	</tr>
	<tr>
		<td>2</td>
		<td>this is second row</td>
		<td>Two</td>
	</tr>
	<tr>
		<td>3</td>
		<td>this is third row</td>
		<td>Three</td>
	</tr>
	<tr>
		<td>4</td>
		<td>this is fourth row</td>
		<td>One</td>
	</tr>
	<tr>
		<td>5</td>
		<td>this is fifth row</td>
		<td>Two</td>
	</tr>
	<tr>
		<td>6</td>
		<td>this is sixth row</td>
		<td>Three</td>
	</tr>

</table>



</body>
</html>

I have three check boxes of types "One", "Two"and "Three" and a table which is having a column as 'Type' that contains three distinct values One, Two and Three across few rows.
My requirement is, based on the check boxes selected or deselected only those rows of the table should be shown for which the value of the 'Type' column match the check box value.

For example,

if check box "One" is selected, those rows having "One" as Type should be shown.
if both "One" and "Three" is selected,those rows having "One" and "Three" as type should be displayed.
again if "Three" is deselected, rows matching "Three" as Type should be hidden,only rows of Type "One" should be shown and so on.

But, I am not able to produce the desired result, attached the code below, can anybody please help.

 <html>

<head>
    <script src ="http://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.    min.js"></script>
    <title>Hello </title>
</head>

<body>
<table>
    <tr>
        <td>
<input type='checkbox' onclick='return filter_type(this);' name='filter'  id="One"  value= "One" />
                 One
     </td>
    <td>
<input type='checkbox' onclick='return filter_type(this);' name='filter'  id="One"  value= "Two" />
                 Two
    </td>
    <td>
<input type='checkbox' onclick='return filter_type(this);' name='filter'  id="One"  value= "Three" />
                 Three
    </td>
    </tr>
 </table>

 <table class="datatbl"  border=1>
    <tr>
        <th>No.</th>
        <th>Content</th>
        <th>Type</th>
    </tr>
    <tr>
        <td>1</td>
        <td>this is first row</td>
        <td>One</td>
    </tr>
    <tr>
        <td>2</td>
        <td>this is second row</td>
        <td>Two</td>
    </tr>
    <tr>
        <td>3</td>
        <td>this is third row</td>
        <td>Three</td>
    </tr>
    <tr>
        <td>4</td>
        <td>this is fourth row</td>
        <td>One</td>
    </tr>
    <tr>
        <td>5</td>
        <td>this is fifth row</td>
        <td>Two</td>
    </tr>
    <tr>
        <td>6</td>
        <td>this is sixth row</td>
        <td>Three</td>
    </tr>

</table>
<style>
.datatbl {
background-color: palegreen;
}
</style>
<script>
function filter_type(box) {
//alert("checked");
 var cbs = document.getElementsByTagName('input');
 var all_checked_types = [];
 for(var i=0; i < cbs.length; i++) {
     if(cbs[i].type == "checkbox") {
             if(cbs[i].name.match(/^filter/)) {
                     if(cbs[i].checked) {
                         all_checked_types.push(cbs[i].value);
                      }
                  }
           }
  }
 //alert("all checked "+ all_checked_types);
 if (all_checked_types.length > 0) {
     $('.datatbl tr').each(function (i, row) {
         var $tds = $(this).find('td'),
         type = $tds.eq(2).text();
         if (type && all_checked_types.indexOf(type) >= 0) {
             //alert("matched");
             $(this).show();
          }
      });
  }
    else {
        $('.datatbl tr').each(function (i, row) {
            var $tds = $(this).find('td'),
            type = $tds.eq(2).text();
            $(this).show();
         });
    }
    return true;
 }  

</script>

</body>
</html>

function filter_type(box) {
//alert("checked");
 var cbs = document.getElementsByTagName('input');
 var all_checked_types = [];
 for(var i=0; i < cbs.length; i++) {
	 if(cbs[i].type == "checkbox") {
        	 if(cbs[i].name.match(/^filter/)) {
                     if(cbs[i].checked) {
                         all_checked_types.push(cbs[i].value);
                      }
                  }
           }
  }
 //alert("all checked "+ all_checked_types);
 if (all_checked_types.length > 0) {
     $('.datatbl tr').each(function (i, row) {
         var $tds = $(this).find('td'),
         type = $tds.eq(2).text();
         if (type && all_checked_types.indexOf(type) >= 0) {
             //alert("matched");
             $(this).show();
          }
      });
  }
    else {
        $('.datatbl tr').each(function (i, row) {
            var $tds = $(this).find('td'),
            type = $tds.eq(2).text();
            $(this).show();
         });
    }
    return true;
}	
.datatbl {
background-color: palegreen;
}
<html>

<head>
	<script src ="http://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.	min.js"></script>
	<title>Hello </title>
</head>

<body>
<table>
	<tr>
		<td>
<input type='checkbox' onclick='return filter_type(this);' name='filter'  id="One"  value= "One" />
                 One
	 </td>
	<td>
<input type='checkbox' onclick='return filter_type(this);' name='filter'  id="One"  value= "Two" />
                 Two
	</td>
	<td>
<input type='checkbox' onclick='return filter_type(this);' name='filter'  id="One"  value= "Three" />
                 Three
	</td>
 	</tr>
 </table>

 <table class="datatbl"  border=1>
	<tr>
		<th>No.</th>
		<th>Content</th>
		<th>Type</th>
	</tr>
	<tr>
		<td>1</td>
		<td>this is first row</td>
		<td>One</td>
	</tr>
	<tr>
		<td>2</td>
		<td>this is second row</td>
		<td>Two</td>
	</tr>
	<tr>
		<td>3</td>
		<td>this is third row</td>
		<td>Three</td>
	</tr>
	<tr>
		<td>4</td>
		<td>this is fourth row</td>
		<td>One</td>
	</tr>
	<tr>
		<td>5</td>
		<td>this is fifth row</td>
		<td>Two</td>
	</tr>
	<tr>
		<td>6</td>
		<td>this is sixth row</td>
		<td>Three</td>
	</tr>

</table>



</body>
</html>

Share Improve this question edited Jan 28, 2016 at 13:30 Mujtaba 1531 silver badge8 bronze badges asked Jan 28, 2016 at 13:15 H.BurnsH.Burns 4192 gold badges9 silver badges22 bronze badges 1
  • Invalid markup id="One" is duplicated – Mark Schultheiss Commented Jan 28, 2016 at 13:56
Add a ment  | 

7 Answers 7

Reset to default 2

I'd use this snipped:

jQuery(document).on('ready', function() {
    var filter_magic = function(e) {
        var trs = jQuery('.datatbl tr:not(:first)');

        trs.hide();
        var showAll = true;
        jQuery('input[type="checkbox"][name="filter"]').each(function() {
            if (jQuery(this).is(':checked')) {
                var val = jQuery(this).val();
                trs.each(function() {
                    var tr = jQuery(this);
                    var td = tr.find('td:nth-child(3)');
                    if (td.text() === val) {
                        tr.show();
                        showAll = false;
                    }
                });
            }
        });
        if (showAll) {
            trs.show();
        }
    };

    jQuery('input[type="checkbox"][name="filter"]').on('change', filter_magic);
    filter_magic();
});

Then you simply have to remove the onclick='return filter_type(this);' stuff from your html.

It does show the rows for checked checkboxes, and displays all rows if nothing is selected. If that behaviour isn't expected, simple change the var showAll = true; to var showAll = false;

And here's a demo: https://jsfiddle/njuzzv6L/2/

As fork of Ahs N's answer:

$("input[type='checkbox']").click(function() {

    var vArr = [];

    $(":checked").each(function() {
        vArr.push($(this).attr("value").toLowerCase());
    });

    $("table:last-child tr").slice(1).each(function() {
        if ($.inArray($(this).find("td").last().text().toLowerCase(), vArr) < 0 || vArr.length == 0) {
            if($(this).is(':visible')) 
                $(this).fadeOut(); //OR $(this).hide();
        }
        else 
            if( !$(this).is(':visible'))
                $(this).fadeIn(); //OR $(this).show();
    });


});

Here is the JSFiddle demo version 2

Solutioned:

			function filter_type(box) {
			 var cbs = document.getElementsByTagName('input');
			 var all_checked_types = [];
			 for(var i=0; i < cbs.length; i++) {
				 if(cbs[i].type == "checkbox") {
						 if(cbs[i].name.match(/^filter/)) {
								 if(cbs[i].checked) {
									 all_checked_types.push(cbs[i].value);
								  }
							  }
					   }
			  }
			 if (all_checked_types.length > 0) {
				 $('#datatbl tr').each(function (i, row) {
					 var $tds = $(this).find('td')
					 if ($tds.length) {
						var type = $tds[2].innerText;
						console.log(type)
						if(!(type && all_checked_types.indexOf(type) >= 0)) {
							$(this).hide();
						 }
						 else {
							$(this).show();
						 }
					  }
				  });
				  
			  }
				else {
					$('#datatbl tr').each(function (i, row) {
						var $tds = $(this).find('td'),
						type = $tds.eq(2).text();
						$(this).show();
					 });
				}
				return true;
			}
#datatbl {
			background-color: palegreen;
		}
<html>
	<head>
		<script src ="http://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
		<title>Hello </title>
	</head>

	<body>
		<table>
			<tr>
				<td>
					<input type='checkbox' onclick='return filter_type(this);' name='filter'  id="One"  value= "One" />One
				</td>
				<td>
					<input type='checkbox' onclick='return filter_type(this);' name='filter'  id="Two"  value= "Two" />Two
				</td>
				<td>
					<input type='checkbox' onclick='return filter_type(this);' name='filter'  id="Three"  value= "Three" />Three
				</td>
			</tr>
		 </table>

		 <table id="datatbl" border=1>
			<tr>
				<th>Unique Id.</th>
				<th>Content</th>
				<th>Type</th>
			</tr>
			<tr>
				<td>1</td>
				<td>this is first row</td>
				<td>One</td>
			</tr>
			<tr>
				<td>2</td>
				<td>this is second row</td>
				<td>Two</td>
			</tr>
			<tr>
				<td>3</td>
				<td>this is third row</td>
				<td>Three</td>
			</tr>
			<tr>
				<td>4</td>
				<td>this is fourth row</td>
				<td>One</td>
			</tr>
			<tr>
				<td>5</td>
				<td>this is fifth row</td>
				<td>Two</td>
			</tr>
			<tr>
				<td>6</td>
				<td>this is sixth row</td>
				<td>Three</td>
			</tr>

		</table>
		
	</body>

</html>

Give checkbox a class .chkbox

$(".chkbox").click(function(){
  var chkboxs = [];
  $.each(".chkbox",function(i,field){
   if(new jQuery(field).prop('checked'))
    chkboxs.push(new jQuery(field).val());
  });
  $.each(".datatbl tr",function(i,field){
   if($.inArray(new jQuery(field).find('td:last').text(),chkboxs))
    new jQuery(field).show();
   else 
    new jQuery(field).hide();
  });
});

I elected not to offer alternate coding - but to show how to make your own code work.

First off, its good practice to be uniform in coding throughout - meaning that in your html some your attributes are inconsistently quoted (single vs double), or in some cases not quoted at all. Since javascript can be picky when it es to targeting elements, its always good to first look for unclean and/or non-uniform html.

That being out of the way, your html ID input tags were not unique. ID tags must be unique.

Lastly, I added an "else" statement to your script so if its not "show"ing, then "hide" the rows.

    <html>
    <head>
    <script src ="http://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <title>Hello </title>

    <style>
        .datatbl {
            background-color: palegreen;
        }
    </style>


   <script>
     function filter_type(box) {
    //alert("checked");
     var cbs = document.getElementsByTagName('input');
     var all_checked_types = [];
     for(var i=0; i < cbs.length; i++) {
         if(cbs[i].type == "checkbox") {
                 if(cbs[i].name.match(/^filter/)) {
                         if(cbs[i].checked) {
                             all_checked_types.push(cbs[i].value);
                          }
                      }
               }
      }

     if (all_checked_types.length > 0) {
         $('.datatbl tr:not(:has(th))').each(function (i, row) {
             var $tds = $(this).find('td'),
             type = $tds.eq(2).text();
             if (type && all_checked_types.indexOf(type) >= 0) {
                 $(this).show();
              }else{
                 $(this).hide();
              }
          });
      }else {
            $('.datatbl tr:not(:has(th))').each(function (i, row) {
                var $tds = $(this).find('td'),
                type = $tds.eq(2).text();
                $(this).show();
             });
    }
    return true;
 }  

</script>



</head>

<body>
<table>
    <tr>
        <td>
            <input type="checkbox" onclick="return filter_type(this);" name="filter"  id="One"  value= "One" />
                 One
        </td>
    <td>
        <input type="checkbox" onclick="return filter_type(this);" name="filter"  id="Two"  value= "Two" />
                 Two
    </td>
    <td>
    <input type="checkbox" onclick="return filter_type(this);" name="filter"  id="Three"  value= "Three" />
                 Three
    </td>
    </tr>
 </table>

 <table class="datatbl"  border="1">
    <thead>
        <tr>
            <th>No.</th>
            <th>Content</th>
            <th>Type</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>this is first row</td>
            <td>One</td>
        </tr>
        <tr>
            <td>2</td>
            <td>this is second row</td>
            <td>Two</td>
        </tr>
        <tr>
            <td>3</td>
            <td>this is third row</td>
            <td>Three</td>
        </tr>
        <tr>
            <td>4</td>
            <td>this is fourth row</td>
            <td>One</td>
        </tr>
        <tr>
            <td>5</td>
            <td>this is fifth row</td>
            <td>Two</td>
        </tr>
        <tr>
            <td>6</td>
            <td>this is sixth row</td>
            <td>Three</td>
        </tr>
    </tbody>
</table>

</body>
</html>

This is how I did it:

$("input[type='checkbox']").click(function() {
  $("tr").fadeIn();

  if ($(":checked").length > 0) {
    var vArr = [];

    $(":checked").each(function() {
      vArr.push($(this).attr("value").toLowerCase());
    });

    $("table:last-child tr").slice(1).each(function() {
      if ($.inArray($(this).find("td").last().text().toLowerCase(), vArr) < 0) {
        $(this).fadeOut();
      }
    });
  }

});

Here is the JSFiddle demo

I see you have an answer selected already however I feel pelled to put in less plicated solution: This shows rows if checked and NOT if unchecked.

I removed the code from the markup.

I simplified the code to the change action event handler.

$('.checkcontainer').on('change', 'input[type="checkbox"]', function() {
  var cbs = $('.checkcontainer').find('input[type="checkbox"]');
  cbs.each(function() {
    var mycheckbox = $(this);
    var isChecked = mycheckbox[0].checked;
    $('.datatbl tr').not(":eq(0)").filter(function() {
        return $(this).find('td').eq(2).text() == mycheckbox.val();
    }).toggle(isChecked);
  });
});

Revised checkbox markup associated with this:

<input type='checkbox' name='filter' id="One" value="One" />

Alternate strategy:

This in my opinion is still not super definitive SO here is a revision using data attributes instead of "text in some column" that might be fragile.

$('.checkcontainer').on('change', 'input[type="checkbox"]', function() {
  var cbs = $('.checkcontainer').find('input[type="checkbox"]');
  cbs.each(function() {
    var mycheckbox = $(this);
    $('.datatbl tr').filter(function() {
        return $(this).data('rowtype') == mycheckbox.val();
    }).toggle(mycheckbox[0].checked);
  });
});

Revised markup snip example for the last code change:

<tr data-rowtype="Three">
   <td>3</td>
   <td>this is third row</td>
   <td>Three is here does not matter</td>
</tr>

NOTE: Either of these will set initial state (hide show) if you simply trigger the change event on any checkbox and it sets for all those checkboxes. Put this in document ready and your are good to go.

 $('.checkcontainer').find('input[type="checkbox"]').eq(0).trigger('change');

Here is a fiddle you can see it in action: https://jsfiddle/6Lk4om0u/

本文标签: javascriptHow to show table rows based on checkbox selectedStack Overflow