I want to make a column visible if its checkbox is selected. I have this function:
function SaveTableSettings() {
var notChecked = [], checked = [];
var table = $('#data-table');
$(":checkbox").each(function() {
if(this.checked){
checked.push(this.id);
} else {
notChecked.push(this.id);
}
});
And I want to use the elements of the "checked" array and change corresponding column visibility with this function :
if (dataTableId == "data-table"&&toShow.length<1) {
alert("in if");
table.column(1).visible(false);
table.column(2).visible(false);
table.column(3).visible(false);
table.column(4).visible(false);
} else {
for (i = 0; i < toShow.length; i++) {
}
}
where "toShow" is the same array with to "checked" I passed it as parameter. I want to make the column which is in the array visible .But I do not know what to do in the for loop. Thanks for any help
You can use the Buttons extension for that purpose, and to be more precise you should use the column visibility plug-in for Buttons.
Here is the basic usage example:
$(document).ready(function() {
$('#example').DataTable( {
dom: 'Bfrtip',
buttons: [
'colvis'
]
} );
} );
You have to include the relevant JavaScript files, for example:
https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js
https://cdn.datatables.net/buttons/1.0.3/js/dataTables.buttons.min.js
https://cdn.datatables.net/buttons/1.0.3/js/buttons.colVis.min.js
Alternatively, use Download builder and include DataTables with Buttons and Column visibility modules.
p.s In case that you use old datatables (1.9.x you should use the ColVis extension
It is hard to debug your code without the markup / HTML, but to me it somehow seems like you are trying to use a sledgehammer to crack a nut.
Instead of id's (?) simply use an attribute to bind the checkbox to a certain column :
<input type="checkbox" data-column="0" checked/>
And in your SaveTableSettings() or whatever :
$("[data-column]").each(function() {
table.column($(this).data('column')).visible($(this).is(':checked'));
})
a small demo -> http://jsfiddle.net/c0o48jmv/1/
The above can easily be changed to target id's instead of column indexes. Simply add id's to your <th>'s
<th id="col0">columnHeader</th>
and refer to those id's instead of the indexes
<input type="checkbox" data-column="#col0" checked/>
http://jsfiddle.net/d9q06cg0/
Related
Here's the JSFiddle of my work: https://jsfiddle.net/pb23Ljd8/5/
I use Bootstrap nav-pills to show all products and categorized too like this:
And I based my checkboxes from here: http://bootsnipp.com/snippets/featured/fancy-bootstrap-checkboxes
I count the number of products checked in between the tabs like this:
jQuery(document).ready(function($) {
jQuery(".select-product").change(function() {
jQuery(".counter").text(jQuery("[type='checkbox']:checked").length);
});
});
But the glyphicon check icons doesn't appear on the second and third tabs for some reason. But when I click the products on the second and third, it increases the counter and also when I view it on the first tab, it is checked.
I just need the products to also be visibly checked on the second and third tabs and not only on the first one so it's not confusing for the user.
Ideas, anyone?
Edit: I fetch the list of products from CMS so it's dynamic. I now understand that the duplication of IDs is causing the problem.
Before we try and resolve this issues, we should break it down and see what the actual problem is.
First, let's check if we remove the content from tab 1b is the issue still present?
Nope, if we remove the checkboxes from the first tab, the checkboxes function normally on the second and third.
Fiddle #1
What if we change the id of the checkboxes (remember ids should be unique).
Notice how Book #1 now works if we change the first checkbox's id to 1a.
Fiddle #2
So now we "know" the issue is likely due to the fact that we are using checkboxes with the same id value (ref). The "issue" is now:
How do we check multiple checkboxes if one is checked
(or something like that)
Here's what I would do:
assign all "like" checkboxes the same class (ex. Book #1 checkboxes will have class b1)
use jQuery/javascript to make sure all that all "like" checkboxes, check and uncheck in unison
Working Example
EDIT
Dynamic values for the classes can be achieved by putting the IDs as classes so the similar products would match. These can be passed to JS like this assuming that $products_id_array is a PHP array that contains all the classes needed.
var productIDs = <?php echo json_encode($products_id_array) ?>;
and then creating the snippet of jQuery code on the fiddle like this
productIDs.forEach(function(val, key) {
jQuery('.' + val).on('change', function(){
jQuery('.' + val).prop('checked',this.checked);
});
})
Try this JS, This will work
jQuery(".select-product").change(function() {
var checkValue = jQuery(this).prop('checked');
$('.select-product#' + jQuery(this)[0].id).each(function() {
if (checkValue == true) {
jQuery(this).prop('checked', true)
} else {
jQuery(this).prop('checked', false);
}
});
var uniqueId = [];
jQuery("[type='checkbox']:checked").each(function() {
uniqueId.push(jQuery(this)[0].id);
});
Array.prototype.getUnique = function() {
var u = {},
a = [];
for (var i = 0, l = this.length; i < l; ++i) {
if (u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
jQuery(".counter").text(uniqueId.getUnique().length);
});
Goal:
If you select "Dates", you can select the dropdownlist for Start date and end date.
If you select "All ... only" the start and end date will be grey colored in the background and you cannot click on the arrow down. These dropdownlists are disable.
Problem:
I don't know how to create it in frontend code.
Info:
*The dropdownlists are created in ASP.net MVC 4
*I'm using jquery 1.10 and bootstrap
<input id="aa" type="radio" name="searchselection" value="all" style="display: inline-block;" checked>
<label for="aa" style="width: 100px; display: inline-block; ">All ...only</label>
<input id="dates" type="radio" name="searchselection" value="dates" style="display: inline-block;">
<label for="dates" style="width: 100px; display: inline-block;">Dates</label>
#{
DateTime myDate = DateTime.Today;
List<SelectListItem> myListSelectListItem_YearStartDate = new List<SelectListItem>();
for (int i = 0; i < 10; i++) {
myListSelectListItem_YearStartDate.Add(new SelectListItem { Text = (myDate.Year - i).ToString(), Value = (i + 1).ToString(), Selected = DateTime.Today.Year == (myDate.Year - i) ? true : false });
}
}
#Html.DropDownList("YearStartDate", myListSelectListItem_YearStartDate)
You could try something like
$(document).on('change', 'input[type=radio][name=searchselection]', function() {
//func body
....
if(this.value == *your choices*){
//disable
$(YourDropdownSelector).attr('disabled', 'disabled');
}else {
//enable again
$(YourDropdownSelector).removeAttr('disabled');
}
});
This is fixed in the following jsfiddle
I've stripped out some of the unneeded HTML attributes (such as the style tags - styles are better applied in css) and also stubbed out the back end code generating the <select> in order to simplify the example and focus on the solution.
Let's look at what's happened:
<select class='js-date-selector' disabled='disabled'>
Firstly, each of your select elements has been edited to add the following two attributes. The class allows targeting from javascript (or JQuery) - note that the js- prefix is not essential, it's just a nice way of keeping your javascript class attributes separate from others. Also, a class is used instead of an id, this is generally best as it is easier to re-use, as we have to in this example.
The disabled attribute is how you mark-up an HTML element so it's greyed out. If you're going to mark 'all dates' as checked on page load and 'all dates' being checked means the selects should be disabled, then your HTML also needs to mark the selects as disabled on load.
Next is the bit that does the toggling:
$('.js-all-or-dates').on('click',function() {
var justClicked = $(this),
dateSelectors = $('.js-date-selector');
if (justClicked.attr('id') === 'aa') {
dateSelectors.attr('disabled', true);
}
else {
dateSelectors.attr('disabled', false);
}
});
Firstly, we bind a function to the click event for each of our .js-all-or-dates radio inputs.
Secondly, we assign variables, using justClicked = $(this) to store a jquery version the element that was just clicked and dateSelectors to store all of our select items, using the class mentioned above
Finally, we look at what was just clicked and if it has the ID of the 'all dates' radio input we set the disabled property on all the select elements.
Also, for good practice and smoother development: === is used for equality; $ function calls are minimised by assigning results to local variables; and the var statement contains comma separated declarations.
I have a series of checkboxes that I populate using a foreach loop (php). The code looks like this:
<input type="checkbox" name="artist_group[]" id="{{$fb_data['fbid']}}" class="input-hidden" data-name="{{$fb_data['name']}}" value="{{$fb_data['fbid']}}" style="display:none;" />
<label for="{{$fb_data['fbid']}}">
<img src="https://graph.facebook.com/{{$fb_data['fbid']}}/picture?width=200&height=200" width="140" height="140" alt="{{$fb_data['name']}}"/>
<article class="artistName">{{$fb_data['name']}}</article>
</label>
What I would like to do is check if any of the checkboxes are checked using javascript. However, I can't do this using the "getElementById" because I want each checkbox to have a unique id (so I can pull the data). I have the name of the checkbox group as an array, so I can send all of the checked boxes to my backend. Can I do the following?:
if (document.getElementByName('artist_group').checked) {
alert("checked");
}
Thank you for your help.
You have iterate over the checkboxes and test whether any of them is checked or not. Note that the method name is getElementsByName (Elements with s):
var boxes = document.getElementsByName('artist_group[]');
var checked = false;
for (var i = 0, l = boxes.length; i < l; i++) {
if (boxes[i].checked) {
checked = true;
break;
}
}
If you are not opposed to newer JavaScript methods, you can also use Array#some:
var checked = Array.prototype.some.call(boxes, function(input) {
return input.checked;
});
With jQuery, it's even simpler:
var checked = $('input[name="artist_group[]"]:checked').length > 0;
Since you tagged jQuery in your question as well, you can use jQuery's $.each.
Just select the elements by the class and not id.
$('.input-hidden').each(function() {
//this will iterate through all checkboxes
if ($(this).is(':checked')) {//Per #Felix's comment, this.checked is a more native way of doing it, I personally just prefer to use $(this) when I'm in jQuery context, to be consistent. Using this.checked is quicker though.
//this will apply just to the checked checkboxes
}
});
You can also get ONLY the selected checkboxes by:
$('input:checked').each(function() {
//this will only apply to selected checkboxes
});
Hope this helps!
As you also used the jQuery tag for your question: IF you're using jQuery anyway (don't just add it only for this task, that's an overkill!):
if ( ! $('input[name="artist_group"]').is(':not(:checked)') ) {
// all are selected
}
A have a checkbox column inside my grid. With another different chechbox I want to toggle the enabling and disabling of the checkbox column inside the grid. The checkbox column is the first column inside my grid.
I have done something like this:
onCheckBoxFieldChange() {
var testGrid = Ext.getCmp('testGrid');
var cm = testGrid.getView().getHeaderCt().getGridColumns();
if (newValue === true) {
cm[0].setDisabled(true);
cm[0].addCls('noClick');
}
else {
cm[0].setDisabled(false);
cm[0].removeCls('noClick');
}
}
CSS:
.noClick {
pointer-events: none;
}
I have tried two approaches. One with the method setDisabled and the other with setting a CSS class. Both approaches did not work. Please help...
Try this:
grid.getView().getHeaderCt().child('checkcolumn').setDisabled(newValue);
This will search for the grid's column whose type is checkcolumn then disable it.
I have a jqGrid with a navBar that has search: true and multipleSearch: true. I would like to add a button to my UI that automatically adds an additional rule to the search.
I've tried manipulating the postData for the filter directly, but values added this way don't show up in the search UI.
I've also tried accessing the search box directly using jQuery, like this:
$('#fbox_list').searchFilter().add();
$('#fbox_list .sf .data input').each(function(index) {
alert($(this).val());
});
But, in addition to feeling hackish, it only works if the user has already clicked on the search button (the fbox_list div is not constructed on load).
Has anyone else dealt with an issue like this?
For the sake of posterity, here is the hack I'm currently using. The grid has an ID of list and the pager has an ID of pager:
jQuery(document).ready(function() {
//Initialize grid.
//Initialize the navigation bar (#pager)
//Hack to force creation of the search grid.
//The filter's ID is of the form #fbox_<gridId>
jQuery('#pager .ui-icon-search').click();
jQuery('#fbox_list').searchFilter().close();
//Example button events for adding/clearing the filter.
jQuery("#btnAddFilter").click(function() {
//Adds a filter for the first column being equal to 'filterValue'.
var postFilters = jQuery("#list").jqGrid('getGridParam', 'postData').filters;
if (postFilters) {
$('#fbox_list').searchFilter().add();
}
var colModel = jQuery("#list").jqGrid('getGridParam', 'colModel');
//The index into the colModel array for the column we wish to filter.
var colNum = 0;
var col = colModel[colNum];
$('#fbox_list .sf .fields select').last().val(col.index).change();
$('#fbox_list .sf .data input').last().val('filterValue');
$('#fbox_list .sf .ops select.field' + colNum).last().val('eq').change();
$('#fbox_list').searchFilter().search();
});
jQuery("#btnClearFilter").click(function() {
$('#fbox_list').searchFilter().reset();
});
});
If you mean the filter toolbar, you can do this: (status is the col name -- so, replace "#gs_status" w/ "#gs_" + your_col_name
jQuery("#distributor_grid").jqGrid('showCol',['status']);
jQuery(".ui-search-toolbar #gs_status")
.val('ALL')
;
$('#distributor_grid').RefreshData(); // triggers toolbar
to clear inputs, selects and reset grid
$("td#refresh_navGrid").click();