Option to check all boxes and hide table row elements - javascript

I've created a simple table where I have the option to select all checkboxes. I would like to have the option to hide individual rows, or hide all the rows when using the select all function. I've managed to get the checkboxes working, but I can't figure out why the table isn't responding to the action. I appreciate any help or insight.
The full code is in this Fiddle. Here is a glance at the jquery and javascript:
<script>
$(document).ready(function() {
$('input[type="checkbox"]').change(function() {
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
});
});
</script>
<script>
function checkedAll() {
var elements = this.form.getElementsByTagName('input');
// iterate and change status
for (var i = elements.length; i--;) {
if (elements[i].type == 'checkbox') {
elements[i].checked = this.checked;
}
}
}
</script>

<script>
$(document).ready(function() {
$('input[type="checkbox"]').change(function() {
var inputValue = $(this).attr("value");
var checked = $(this)[0].checked;
$("tr").each(function() {
if($(this).find("td:eq(0)").html() === inputValue.toString()) { // this checks the first cell of each row of the table for a match
if(checked) { //instead of just toggling, you check the status and then show/hide
$(this).hide();
} else {
$(this).show();
}
}
});
});
});
</script>
<script>
function checkedAll() {
var elements = this.form.getElementsByTagName('input');
// iterate and change status
for (var i = elements.length; i--;) {
if (elements[i].type == 'checkbox') {
elements[i].checked = this.checked;
$(elements[i]).trigger("change"); // this triggers the function above
}
}
}
</script>
This should work for you. The .each loop will iterate through the rows and hide the ones where the first td is the value to be hidden.

Related

Adding select/deselect all to dynamic tabular form

I have a form which contains buttons to add and delete rows. My javascript function to check all checkboxes works for the first row, but once I add more rows to the form, the first row is still the only one that gets checked.
Any tips?
Here is my javascript function:
<code>
//checks all rows
function checkAll() {
var masterCheck = document.getElementById('masterCheck');
var on = false;
if(masterCheck.checked==true) {
document.getElementById('checkbox').checked=true;
} else {
document.getElementById('checkbox').checked=false;
}
}
</code>
And here is the form:
http://crimsonroot.com/files/freelance/new.html
Any help is appreciated!
I found out what was wrong! #Mohammed your answer really helped. There were just one or two syntax errors that I found. In order to check and uncheck all of the boxes, I needed to add a boolean variable as an input to the function as follows:
//checks all rows
function checkAll(bool) {
var masterCheck = document.getElementById('masterCheck');
var allcheck = document.getElementsByClassName('checkbox');
var on = false;
for (var i = 0; i < allcheck.length; i++) {
if (masterCheck.checked == true) {
allcheck[i].checked = true;
} else {
allcheck[i].checked = false;
}
}
}
For some reason, this was the final piece to the puzzle. Thanks for all of the help!
You should try something like this.
$("#masterCheck").click(function () {
$('input:checkbox').not(this).prop('checked', this.checked);
});
Since document.getElementById() returns first element, because id cannot be used more than one. To make it usable, add a class checkbox and try the following code:
//checks all rows
function checkAll() {
var masterCheck = document.getElementById('masterCheck');
var allcheck = getElementsByClassName('checkbox');
var on = false;
for (var i = 0; i < allcheck.length; i++) {
if (masterCheck.checked == true) {
allchecked[i].checked = true;
} else {
allchecked[i].checked = false;
}
}
}

Reset button for JQuery table row filter

I have a table on my page, and a filtering text box above it that works fantastic, using the following JQuery:
$("#searchInputCompanies").keyup(function () {
//split the current value of searchInput
var data = this.value.split(" ");
//create a jquery object of the rows
var jo = $("#cBody").find("tr");
if (this.value == "") {
jo.show();
return;
}
//hide all the rows
jo.hide();
//Recusively filter the jquery object to get results.
jo.filter(function(i, v) {
var $t = $(this);
for (var d = 0; d < data.length; ++d) {
if ($t.text().toLowerCase().indexOf(data[d].toLowerCase()) > -1) {
return true;
}
}
return false;
})
//show the rows that match.
.show();
$('#selectAllCompanies').prop('checked', '');
}).focus(function () {
this.value = "";
$(this).css({
"color": "black"
});
$(this).unbind('focus');
}).css({
"color": "#C0C0C0"
});
How can I set up a Reset Filter button for this?
Uhh, this is quite a bad implementation :(
First, you need to change the event for $("#searchInputCompanies") to make it all a bit easier. So, it will become $("#searchInputCompanies").on("input", function() {...
$("#resetAction").on("whatEventYouWant", function() {
$("#searchInputCompanies").val("").trigger("input");
});
This will trigger input event on $("#searchInputCompanies") and because the text box is empty all rows will become visible.

Occur if 3 button are clicked and disable other button

I have in a html page 5 button named 1,2,3,4 and 5.If 3 button are clicked the other button must be disabled.
var clicking=0;
$(document).ready(function(){
$('button').click(function(){
clicking++;
$(this).toggleClass("active");
if(clicking==3){
$('button').click(function(){
$(this).toggleClass("nothing");
})
}
})
})
I tried with this script but it don't work because all the button can be clicked.The if is ignored.
i want that only 3 of this 5 button can be clicked and the other must become disabled.
EDIT: shortened the code
I think this is what you want? Count the number of buttons with .active. If it's three or more, disable all buttons that don't have .active.
JS:
$('button').on('click', function() {
$(this).toggleClass('active');
$('button').prop('disabled',false);
if ($('.active').length >= 3) {
$('button:not(.active)').prop('disabled',true);
}
});
Here's a fiddle.
You should do something like this :
var clicking=0;
$(document).ready(function(){
$('button').click(function(){
clicking++;
$(this).toggleClass("active");
if(clicking==3){
$('button').each(function(){
if(!$(this).hasClass("active")){
$(this).addClass("inactive");
}
});
}
});
});
I didn't try it, but I think you like for something similar.
Ok i am not a master of jquery but i came up with a simple logic to implement what you want to achieve, that is disabling all the other buttons that haven't been clicked after three clicks. Here's my working code:
var count = 0;
var ids = new Array();
$(document).ready(function(){
$('button').click(function(){
ids[count] = this.id;
count++;
if(count == 3){ //three buttons clicked, now time to disable the remaining buttons
for(var i=0; i<$('button').length; i++){ //we'll check for all buttons
var id = $('button')[i].id;
var flag = true;
for(var j=0; j<ids.length; j++){ //checking all the buttons against the buttons that got clicked
if(id == ids[j])
flag = false; //button has been clicked (won't be disabled)
}
if(flag){
$("#"+id).attr("disabled", true); //disabling button
}
}
}
})
})
It's very self explanatory and i added lots of comments but still what i did is:
save the ids of buttons that got clicked, then after three clicks, disabling all the buttons who's ids don't match with the saved ids. Pretty simple.. but im sure you can make the code better as i'm not too good at jquery.
See the Working DEMO here
My sugestion is to use an array so you know witch buttons were clicked.
$(document).ready(function(){
var clickedbuttons = [];
$('button').click(function(){
$(this).toggleClass("active");
var idx = jQuery.inArray($(this).attr("id"), clickedbuttons );
if(idx == -1)
clickedbuttons.push($(this).attr("id"));
else clickedbuttons.splice(idx,1);
if(clickedbuttons.length == 3) {
$('button').each(function() {
var index = jQuery.inArray($(this).attr("id"), clickedbuttons );
if(index == -1)
$(this).attr("disabled", "disabled");
});
}
else {
$('button').each(function() {
$(this).removeAttr("disabled");
});
}
});
})
I'm assuming each button has an id. This will work as you want but you have to have an id in every button.
If you do not want to reenable change accordingly
$(document).ready(function(){
var clickedbuttons = [];
$('button').click(function() {
var idx = jQuery.inArray($(this).attr("id"), clickedbuttons );
if(idx == -1) {
clickedbuttons.push($(this).attr("id"));
$(this).toggleClass("active");
}
if(clickedbuttons.length == 3) {
$('button').each(function() {
var index = jQuery.inArray($(this).attr("id"), clickedbuttons );
if(index == -1)
$(this).attr("disabled", "disabled");
});
}
else {
$('button').each(function() {
$(this).removeAttr("disabled");
});
}
});
})

Merging 4 similar click functions into one

Here are 4 functions I use to improve the usability of a table by:
If cell contains a checkbox and you click outside of a checkbox
The the tr contains data-url then the whole row is "clickable"
with CSS hover effect and redirects on click.
If the last column in the table contains a relative/absolute URL
then also redirects on click.
Check all checkboxes.
Here's my code:
// Click table cell auto check checkbox
$('table tr td').has("input[type=checkbox]").click(function(event) {
// Onl call this if click outside of the checkbox itself
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
// Table row click
$('table tr[data-url]').each(function(){
var url = $(this).attr("data-url");
if(url.length){
$(this)
.addClass("clickable")
.find("td").click(function(){
window.location = url;
return false;
});
}
});
// Double click row, open edit link
$('table:not(.noDoubleClick) tr td').dblclick(function(e) {
var linkEl = $(this).parents('tr').find('td:last-child a');
var linkElHref = linkEl.attr('href');
// Check if has href and http protocol
if(!linkElHref.length || linkEl.prop('protocol').indexOf("http") !== 0){
e.preventDefault();
return false;
}
if (linkElHref && linkEl.attr('onclick') === undefined && !linkEl.hasClass("popme")) {
document.location = linkElHref;
} else {
linkEl.click();
}
});
// Check all checkboxes
$('table input[type=checkbox][name^="checkall"]').live("click",function() {
var parent = $(this).parents('table');
if(!$(this).parents('table').length){
parent = $(this).parents("form");
}
parent.find(':checkbox[name^="' + $(this).attr("data-name") + '"]').prop("checked", this.checked);
});
Q: how can I modify this into one function so that jquery only has to search for tables once?
Example jsfiddle
Thanks for every bodies suggestions I have ended up taking a slightly different approach:
$('table').each(function(){
var $table= $(this), $cell, $row;
// TABLE ROWS
$table.find('tr').each(function(){
$row = $(this);
// Row click redirect to data-url
var url = $row.attr("data-url");
if(url && url.length){
$row.addClass("clickable").find("td").click(function(){
window.location = url;
return false;
});
}
// TABLE HEADING CELLS
$row.find('th, thead td').each(function(){
$cell = $(this);
// Check all checkboxes
$cell.find('input.checkall').live("click",function() {
var parent = $(this).parents('table');
if(!$(this).parents('table').length){
parent = $(this).parents("form");
}
parent.find(':checkbox[name^="' + $(this).attr("data-name") + '"]').prop("checked", this.checked);
});
});
// TABLE CELLS
$row.find('td').each(function(){
$cell = $(this);
// Check checbox onClick
if($cell.find("input[type=checkbox]")){
$cell.click(function(e) {
if(e.target.type !== 'checkbox') $(':checkbox', this).trigger('click');
});
}
// Double click open edit link
if(!$table.hasClass("noDoubleClick")){
$cell.dblclick(function(e){
var linkEl = $(this).parents('tr').find('td:last-child a');
var linkElHref = linkEl.attr('href');
// Check if has href and http protocol
if(linkElHref && (!linkElHref.length || linkEl.prop('protocol').indexOf("http") !== 0)){
e.preventDefault();
return false;
}
if (linkElHref && linkEl.attr('onclick') === undefined && !linkEl.hasClass("popme")) {
document.location = linkElHref;
} else {
linkEl.click();
}
});
}
}); // end CELLS
}); // end ROWS
}); // end TABLE
You should use .on , .live is being deprecated:
$(document).on('click', 'table tr td', function(event)
{
if( $(this).has("input[type=checkbox]"))
{
if (event.target.type !== 'checkbox')
$(':checkbox', this).trigger('click');
}
});
// Table row click
$(document).on('click', 'table tr[data-url] td', function(e)
{
var url = $(this).parent().attr("data-url");
if(url.length)
{
window.location = url;
return false;
}
});
$(document).on('dblclick', 'table:not(.noDoubleClick) tr td', function(e) {
debugger;
var linkEl = $(this).parents('tr').find('td:last-child a');
var linkElHref = linkEl.attr('href');
// Check if has href and http protocol
if(!linkElHref.length || linkEl.prop('protocol').indexOf("http") !== 0){
e.preventDefault();
return false;
}
if (linkElHref && linkEl.attr('onclick') === undefined && !linkEl.hasClass("popme")) {
document.location = linkElHref;
} else {
linkEl.click();
}
});
// Check all checkboxes
$(document).on('click', 'table input.checkall', function() {
var parent = $(this).parents('table');
if(!$(this).parents('table').length){
parent = $(this).parents("form");
}
parent.find(':checkbox[name^="' + $(this).attr("data-name") + '"]').prop("checked", this.checked);
});​
I have made the basic stubs here, i dont want to rewrite all your code.
$(document).ready(function(){
$('table').each(function(){
var table = $(this);
table.find('tr').each(function (){
var tr = $(this);
tr.find('td').each(function(){
var td = $(this);
td.has("input[type=checkbox]").click(function(event) {
// Only call this if click outside of the checkbox itself
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
});
});
});
});
​
The logic is: Find all tables, loop through all the tr's and then the td's. I've did your first function and hope that explains how it could be used?
​
The best thing to do in this case is to:
Get all of the tables in the page
Loop through each table
Find and apply logic to the individual elements as needed
$('table').each(function(){
var table = $(this),
rows = table.find('tr[data-url]'),
cells = table.find('td'),
all = table.find('input[type=checkbox][name^="checkall"]'),
edit = table.is('.noDoubleClick');
cells.each(function(){
//Apply your logic here
if(edit === true){
//Apply your logic to this cell here
}
});
rows.each(function(){
//Apply your logic to this row here
});
all.on('click',function(){
//Apply your logic here
});
});

Checkbox click script - [SHIFT] check/uncheck range, [CTRL] check/uncheck all -- based on select name?

Would anyone know of a ready-made script or plugin providing:
-Shift click for check/uncheck all in range
-CTRL click to select or unselect all
That can works off the check inputs 'name' (instead of all on a page or all inside a div):
input[name='user_group[]']
input[name='record_group[]']
I've been using a couple of scripts (javascript and jQuery) but they're based on all checkboxes in a div or table and I'm not smart enough to roll my own or modify another script. Google searching on this has been a little difficult (too many common terms I think)...
Thanks Much Appreciated!
I started playing around with this script, although it's missing a CTRL+Click feature (select all/none control).
In it's original form it works against all checkboxes on a page. I changed the "$('input[type=checkbox]').shiftClick();" linke to "$("input[name='selected_employees[]']").shiftClick();" and as far as I can tell it seems to be working perfectly now against only the single checkbox group.
The only flaw (for my requirements) is there is not a CTRL+Click function to toggle check or un-check all checkboxes in the group.
<script type="text/javascript">
$(document).ready(function() {
// shiftclick: http://sneeu.com/projects/shiftclick/
// This will create a ShiftClick set of all the checkboxes on a page.
$(function() {
$("input[name='selected_employees[]']").shiftClick();
// $('input[type=checkbox]').shiftClick();
});
(function($) {
$.fn.shiftClick = function() {
var lastSelected;
var checkBoxes = $(this);
this.each(function() {
$(this).click(function(ev) {
if (ev.shiftKey) {
var last = checkBoxes.index(lastSelected);
var first = checkBoxes.index(this);
var start = Math.min(first, last);
var end = Math.max(first, last);
var chk = lastSelected.checked;
for (var i = start; i < end; i++) {
checkBoxes[i].checked = chk;
}
} else {
lastSelected = this;
}
})
});
};
})(jQuery);
});
</script>
I believe this should work!
Working demo on jsFiddle: http://jsfiddle.net/SXdVs/3/
var firstIndex = null;
$(":checkbox").click(function(e) {
$this = $(this);
if (e.ctrlKey) {
if ($this.is(":checked")) {
$("input[name='"+ $this.attr("name") +"']").attr("checked", "checked");
} else {
$("input[name='"+ $this.attr("name") +"']").removeAttr("checked");
}
} else if (e.shiftKey) {
$items = $("input[name='"+ $this.attr("name") +"']");
if (firstIndex == null) {
firstIndex = $items.index($this);
} else {
var currentIndex = $items.index($this);
var high = Math.max(firstIndex,currentIndex);
var low = Math.min(firstIndex,currentIndex);
if ($this.is(":checked")) {
$items.filter(":gt("+ low +"):lt("+ high +")").attr("checked", "checked");
} else {
$items.filter(":gt("+ low +"):lt("+ high +")").removeAttr("checked");
}
firstIndex = null;
}
}
});

Categories

Resources