Jquery checkboxes within containing table selector question - javascript

My current code:
<script type="text/javascript">
function checkAll(checked) {
$("input[type='checkbox']:not([disabled='disabled'])").attr('checked', checked);
}
</script>
<input type="checkbox" id="cbxSelectAll" onclick="checkAll(this.checked);" />
The short version:
How do I modify the function call and method above to check all checkboxes inside a table containing the checxbox form element.
The long version:
I am creating a WebUserControl containing a grid view in asp.net that is going to have a delete option. I would like the delete to be a series of checkboxes with one a box in the header to select all of them. What this amounts to for non ASP.NET people is a table with a header row that has a checkbox and every row also has a checxbox.
I have used the above code to check all boxes on the entire page. That won't work here though because I want to have multiple of these on the page at once each working independently. I know I could use a selector to select all the boxes if I ID'd the table but that would require some coding to name the table uniquely and then put that name in the script block.
Really what I would like is to modify the script above to check all checkboxes in the containing table of the "select all" box. The table containing the checkbox could be nested within others but I don't see any being nested within it, or if there are and the nested table also contains checxboxes I don't care if they also get selected.
Thanks for your help.

First, don't mix your HTML and your Javascript. Use event handler binding instead.
Second, use closest to get the nearest ancestor element of a particular type:
$(document).ready(function(){
$('#cbxSelectAll').click(function() {
$(this)
.closest('table') // get the parent table element
.find("input:checkbox:enabled") // find children that match the selector
.attr('checked', this.checked); // set their checked value
});
});

Change your inline attribute to this:
<input type="checkbox" id="cbxSelectAll" onclick="checkAll.call(this);" />
And your checkAll() to this:
function checkAll() {
$(this).closest('table').find("input:checkbox:enabled").attr('checked', this.checked);
}
Using .call(), it is called from the context of the element clicked.
Then the jQuery gets the closest()(docs) <table> and finds the inputs using the checkbox-selector(docs) and the enabled-selector(docs) .
Then when using the attr()(docs) method, you can use this.checked to set the checkboxes to the current state of the one checked.

You can find the table containing the select all using .closest
function checkAll(checked) {
var $table = $(this).closest('table');
$table.find("input[type='checkbox']:not([disabled='disabled'])")
.attr('checked', checked);
}
If there might be several nested tables it's often easiest to specify the one you want with a class, e.g. $(this).closest('table.tableOfCheckboxes'); where you add class tableOfCheckboxes to the table you want to find.

Related

Bug when trying to update an HTML table value in the DOM

I am trying to implement a simple update functionality for the values in my table. I have an edit button, which triggers a modal where I edit the values and save them. In order the values to be immediately update in the DOM I am using the following jquery code on save:
$('#lblEditDeleteProducts').find("tr .nameDom").text("new val");
$('#lblEditDeleteProducts').find("tr .brandDom").text("new val");
$('#lblEditDeleteProducts').find("tr .priceDom").text("new val");
The problem is that with this code intead of one row in my table all the rows get updated with the "new value". I am very new to jquery and I am out of ideas how to solve this, so any help will be appreciated.
Here is my table structure :
As there is not much information of your HTML code
var selectedTR;
$("#lblEditDeleteProducts tr").click(function(){
selectedTR=$(this);
//init your modal pop up here or do it globally
})
Let assume the ID of save button is #save
$("#save").click(function(){
selectedTR.find(".nameDom").text("new val"); // get relative value from the mdoal input
selectedTR.find(".brandDom").text("new val");
selectedTR.find(".priceDom").text("new val");
})
If you are interested you can use this plugin also (advanced feature) datatable inline edit
The selectors that find is using are too general, so they're selecting all matching rows.
$('#lblEditDeleteProducts').find("tr .nameDom").text("new val");
Here's what jQuery is doing with that particular line of code (the same thing applies to all the others, too):
Get lblEditDeleteProducts by ID
Using that node, find() all descendant elements that match the selector tr .nameDom
Update the text of all nodes that it finds.
In your case, that selector matches every element in every row because they're all descendants of #lblEditDeleteProducts; there's no way to filter out just those you want with the code that you've written.
You'll need a way of explicitly determining which row to update.
Based on your comment that the edit button is in the each row, you can reference the corresponding row with closest
$("EDIT BUTTON SELECTOR").click(function(){
var $btn = $(this);
var $row = $btn.closest("tr");
$("DIALOG SELECTOR").dialog({
buttons:{
Save: function(){
//bunch of stuff
$row.find("td.nameDom").text("new val");
}
}
});
});

jQuery: Put dynamically generated input values to span/div

I'm trying to create form for printing with dynamically generated inputs.
Contents of the fields is shown later in PreviewDiv.
It works fine as long as I specify where they should be, for example:
$('#Prw_CapacityA_1').text($('#CapacityA_1').val());
$('#Prw_CapacityB_1').text($('#CapacityB_1').val());
$('#Prw_CapacityC_1').text($('#CapacityC_1').val());
But if the user creates 100 fields this would be a lot of code to write.
There must be other methods to fix this dynamically, for example:
$('#Prw_CapacityA_'+ counter).text($('#CapacityA_'+ counter).val());
Here's the js fiddle
You could try using attribute starts with selector to select the elements starting with the specific id's and then loop through them using the each() function.
There is no need to have html within your preview table. You can generate it when the user clicks on preview. Modified fiddle
$('#PreviewButton').click(function(){
var capB = $('td input[id^=CapacityB_]');
var capC = $('td input[id^=CapacityC_]');
var table = $("#AddFieldsToPreviewDiv");
table.empty(); //build table everytime user previews so that previously appended values are removed
table.append('<tr><td>ID</td><td>Text 1</td><td>Text 2</td><td>Text 3</td></tr>');
$('td input[id^=CapacityA_]').each(function(i){
table.append('<tr><td>#'+(i + 1)
+'</td><td>'+$(this).val()
+'</td><td>'+$(capB[i]).val()
+'</td><td>'+$(capC[i]).val()
+'</td></tr>');
});
// Show PreviewDiv and hide FormDiv if PreviewButton clicked
$('#PreviewDiv').show();
$('#FormDiv').hide();
});
You could try giving them a unique class (Normally I'd suggest ID but you're using one) say a class of "getinfo"
You could then try the .each() function
https://api.jquery.com/each/
$( ".getinfo" ).each(function( index ) {
var text = $(this).val();
alert(text);
});
This will make an alert box for every element it finds with the class 'getinfo' and then retrieve the value and display it, I hope this gives you a better idea.
If the amount of inputs can change from one page load to the next then you need to use a loop, rather than pulling all the values by 'hand', More code will help better understand what you're trying to achieve and from what.

Access hidden checkboxes with javascript and jQuery

I have a datatable, where each row has a checkbox. I'm trying to add select-all functionality to this set of checkboxes, for which I created the following function:
function selectAll() {
$(':checkbox').each(function() {
this.checked = true;
});
}
This works to select all checkboxes which are currently visible, however, the checkboxes on other pages of the datatable are not selected. I know that there is an issue with these checkboxes in general, since to submit the form and include those checkboxes, I had to add the following function:
$('form').submit(function() {
oTable1 = $('#mytable').dataTable();
$(oTable1.fnGetHiddenNodes()).find('input:checked').appendTo(this);
});
So I suspect that in order to check these checkboxes, I will somehow have to append them to the DOM, at least temporarily, check them off, and then remove them from the DOM. Or is there something simpler that I can do?
I managed to get this work using the following:
oTable1 = $('#mytable').dataTable();
$(oTable1.fnGetNodes()).find(':checkbox').attr('checked',true);
As an alternative, you can also use
$(oTable1.fnGetFilteredNodes()).find(':checkbox').attr('checked',true);
which will apply the "select-all" only to the rows that match the current filter.

Cloning table row in Jquery

Running into a bit of a brick wall with jquery, I currently have the following code:
http://jsfiddle.net/uSLhb/1/
The clone method being:
$("#addMore").click(function() {
$('.user_restriction:last').clone().insertAfter(".user_restriction:last");
return false;
});
As you can see I have it set up so you can easily clone the row.
The problem I am facing is showing the correct select list (In the 'Field' column) in the new cloned elements, depending on what field they select from the first select (In the 'table' column) field in the row.
Wondering if anyone can help me find a solution, thanks!
The problem you are facing occurs, because you are using IDs for your selects.
IDs must be unique in a page, otherwise you'll run into trouble. If you're cloning a select with an id, the id will be cloned too, thus producing an invalid document.
Have a look at the example I created on JsBin
Markup:
<tr class="user_restriction">
<td>
<select name="table[]" class="userselect">
<option value="" selected>---</option>
<option value="members">Members</option>
<option value="staff_positions">Staff Positions</option>
</select>
</td>
<!-- and so on, basically just changed ids to classes -->
</tr>
I changed all the IDs to classes and altered the change-handler, because this was your second problem.
An event-handler gets bound to the elements that are selected, not to those you add afterwards. This is a proper use-case for event-delegation, when the handler is bound to a parent and catches, in this example, the change event from a child select-element, no matter when it was added to the DOM.
Using jQuery, this is a way to achieve this:
$('table.table').on('change', '.userselect', function() {
var activeRow = $(this).parents('tr');
activeRow.find('td').eq(1).find('select').hide();
if(this.value.length === 0){
activeRow.find('td').eq(1).find('select').eq(0).show();
}else{
activeRow.find("." + this.value).show();
}
});
The handler is bound to your table - element, .userselect is a class I added to the first select in a row. So every change on an element that was added later would be handled too. In the handler, I changed the behaviour to affect only the actual table-row, not the whole table.
Working example here - I had to use jsbin as fiddle was playing up!
Clone does not maintain the selected state, so you'll need to grab the value before cloning and set it after.
Your click now becomes:
$("#addMore").click(function() {
var value = $('.user_restriction:last').find('select').val();
$('.user_restriction:last').clone().insertAfter(".user_restriction:last");
//alert(value);
$('.user_restriction:last').find('select').val(value);
return false;
});

how to hide field in same row as field its dependent on

I'm pretty novice at jquery but I have a table with a field in each row that is dependent on another field (checkbox) in the row. Since its in a table I need to handle them in bulk. I don't think I'm using next() correctly but I'm trying to grab the next .subnet_mask since it will be the one in the same row as hide it. I'll also have to update it once I get that far so that it handles hiding and showing if the checkbox is checked or not.
$(function() {
$('.dhcp').each(function() {
$(this).click(function(){
$('.subnet_mask').next().hide();
});
});
});
Any help is appreciated!
EDIT: ok ok :) well the page is actually written in VisualForce (for salesforce). For simplicty sake lets say its just a form wrapped around a table (up to 20 rows representing different records) displaying a checkbox field with the class .dhcp and a field after it called .subnet_mask that should be shown/hidden based on the checkbox. Is that helpful?
I'd rather do this
$('.dhcp').on('click', function() {
$(this).nextAll('.subnet_mask').toggle();
});
Then you show/hide the next .submask (assuming one .submask per <tr>) each time you click the .dhcp
I'd suggest the following, though this suggestion may well change once I see the relevant HTML:
$('.dhcp').click(
function(){
$(this).closest('tr').find('.subnet_mask').hide();
});
This assumes that there will be only one .subnet_mask element per row (otherwise this will hide all of them) in response to the click event. You mention that this depends upon a checkbox, so perhaps the following would be better, using the change() method:
$('.dhcp').change(
function(){
var that = $(this);
if (that.is(':checked')) {
that.closest('tr').find('.subnet_mask').hide();
}
else {
that.closest('tr').find('.subnet_mask').show();
}
});
References:
change().
:checked selector.
click().
closest().
find().
hide().
is().
show().
You're using next incorrectly. It should be more like this:
$(function() {
$('.dhcp').each(function() {
$(this).click(function(){
$(this).next('.subnet_mask').hide();
});
});
});
For this case, I'm assuming that .dhcp and .subnet_mask are indeed siblings, wit the latter coming immediately after the former. Otherwise, .nextAll() can be substituted for .next()
Edited as per point below.

Categories

Resources