I am quite new with jQuery, the following code is a collage of 2 different codes I found to achieve my objective
I have a table with a an image that when clicked it removes a table row, that is the first part of the below code.
The second part of the script finds the sum of all the table rows
I am trying to make it so that when you remove a row the sum also changes accordingly. So when you remove a table row the amount in that table row will be subtracted from the total. I need the sum to change according to the row you delete
jQuery part that removes the table row
$(document).ready(function(){
$('table#FeatureMatrix td a.delete').click(function()
{
{
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
parent.fadeOut('slow', function()
{$(this).remove();});
return false;
}
});
Part of jQuery that calculates the sum of all table rows
$(document).ready(function() {
//this calculates values automatically
calculateSum();
$(".txt").live("keydown keyup", function() {
calculateSum();
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
else if (this.value.length != 0){
}
});
$("#sum").html(sum.toFixed(2));
}
If somebody wants to see the example page on the web this is the link http://webiceberg.net/Prices.php, you can also view the source of the page if you need more detail on the code.
You simply need to call calculateSum() when you delete the row (tidied the code up a bit as well!):
$('table#FeatureMatrix td a.delete').click(function() {
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
parent.fadeOut('slow', function() {
$(this).remove();
calculateSum();
});
return false;
});
Note that it has to be done after the $(this).remove() inside the callback otherwise you will call calculate before actually removing the row.
If you are concerned about it calling calculateSum directly then fire a custom event and listen for that and then recalculate:
$('table#FeatureMatrix td a.delete').click(function() {
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
parent.fadeOut('slow', function() {
$(this).remove();
$.event.trigger("rowDeleted"); // fire custom event
});
return false;
});
Then listen for this event:
$('#sum').bind('rowDeleted', function() { // listen for custom event
calculateSum();
});
Try the following:
$("table#FeatureMatrix").bind("DOMSubtreeModified", function() {
calculateSum();
});
This will recalculate the sum each time the table is modified (It will work for rows added too)
Related
I think I have a simple problem here but my jquery is somewhat limited.
I'm using this script to check all the checkboxes in my table rows which are handled by datatables (including the hidden ones from deferred rendering)
It's working for the checking portion, but the unchecking is not working when I want to deselect the boxes. How can I tweak what I have to to uncheck the boxes correctly?
Heres my code:
$('#selectall').on('click', function() { //on click
if(this.checked) { // check select status
var cells = dTable.cells( ).nodes();
$( cells ).find(':checkbox').prop('checked', $(this).is(':checked'));
} else {
var cells = dTable.cells( ).nodes();
$( cells ).find(':checkbox').prop('checked', $(this).is(':not(:checked)'));
}
});
Thanks in advance
I'm partial to this version myself:
$('#selectall').on('click', function() { //on click
var cells = dTable.cells( ).nodes();
$( cells ).find(':checkbox').prop('checked',this.checked);
});
Looks to me like your uncheck code evaluates to true.. which means it would be checking them. Try this instead:
$('#selectall').on('click', function() { //on click
if (this.checked) { // check select status
var cells = dTable.cells( ).nodes();
$( cells ).find(':checkbox').prop('checked',true);
} else {
var cells = dTable.cells( ).nodes();
$( cells ).find(':checkbox').prop('checked',false);
}
});
I am currently using Footables to display tabular data. Each row has a checkbox. There is one master checkbox that selects all. I am running into some difficulties. The table has a filter. When I apply the filter and try to check all checkboxes within that filter it wont work. Also, since I am able to check all checkboxes at once is there away to uncheck all checkboxes? EXAMPLE
Checkbox function
$(document).on('change','input[name="check_all"]',function() {
$("input[type=checkbox]").attr('checked', true);
});
$(document).on('change','select',function() {
$('input[type=checkbox]').attr('checked', false);
});
table filter
$(function () {
$('table').footable().bind({
'footable_filtering': function (e) {
var selected = $('.filter-status').find(':selected').text();
if (selected && selected.length > 0) {
e.filter += (e.filter && e.filter.length > 0) ? ' ' + selected : selected;
e.clear = !e.filter;
}
},
'footable_filtered': function() {
var count = $('table.demo tbody tr:not(.footable-filtered)').length;
$('.row-count').html(count + ' rows found');
}
});
$('.clear-filter').click(function (e) {
e.preventDefault();
$('.filter-status').val('');
$('table.demo').trigger('footable_clear_filter');
$('.row-count').html('');
});
$('.filter-status').change(function (e) {
e.preventDefault();
$('table.demo').data('footable-filter').filter( $('#filter').val() );
});
});
use .prop() instead of .attr()
Check/uncheck only the visible rows
set the checked status to the select all checkboxes state
Try
$(document).on('change', 'input[name="check_all"]', function () {
$(".footable tr:visible input[type=checkbox]").prop('checked', this.checked);
});
try this one with not selecter which will select except the class .footable -filtered
$(document).on('change', 'input[name="check_all"]', function () {
$(".footable tr:not(.footable-filtered) input[type=checkbox]").prop('checked', this.checked);
});
I have a gridview and I've implemented jquery.ui.sortable on it.
I've successfully assigned values for a custom attribute "printorder" which is used for its order in the list. What I need to know is how to get the previous or next attribute value for print order after I drop the sortable item. Here's what I've done so far but it doesnt work as it should:
$(function () {
$("#ListItems tbody").sortable({
start: function (event, ui) {
originalIndex = $("#ListItems tr.ListItem").index(ui.item);
originalPrintOrder = $(ui.item).attr('printorder');
},
stop: function (event, ui) {
endIndex = $("#gvInvItems tr.ListItem").index(ui.item);
if (endIndex < originalIndex) {
newPrintOrder = $(ui.item).prev().attr('printorder') + 1;
}
if (endIndex > originalIndex) {
newPrintOrder = $(ui.item).next(1).attr('printorder') - 1;
}
if (originalIndex == endIndex) {
return;
}
ChangeOrder(originalPrintOrder, newPrintOrder, $(ui.item).attr('ItemGUID'));
},
handle: ".dragHandle"
});
$("#ListItems tbody").sortable({
items: 'tr.RowStyle, tr.AltRowStyle'
});
});
You can look at the Api-Documentation. Use the update event and jQuery .next() and .prev() to get the elements:
http://jsfiddle.net/CZtLe/2/
$(function () {
$('ul').sortable({
update: function (event, ui) {
var prevElement = ui.item.prev();
var nextElement = ui.item.next();
$('span#prev').html(prevElement.html());
$('span#next').html(nextElement.html());
}
});
});
It seems that my code works well as. The problem was that I was adding strings so if I moved 5 rows 5 the code should add 1 to the previous row so it should be 4 + 1 = 5. But since I did not convert it to int (Number()) it only appended each other as strings so 4 + 1 = 41.
Noob mistake really. Thanks!
I have an HTML table with a checkbox in each row.
I want to loop over the table and see if there are any checkboxes that are checked.
The following does not work:
$("#save").click( function() {
$('#mytable tr').each(function (i, row) {
var $actualrow = $(row);
checkbox = $actualrow.find('input:checked');
console.log($checkbox);
});
This prints in the console the following:
[prevObject: jQuery.fn.jQuery.init[1], context: tr, selector: "input:checked", constructor: function, init: function…]
per row regardless of whether any checkbox is checked.
Update
Same issue with:
$('#mytable tr').each(function (i, row) {
var $actualrow = $(row);
$checkbox = $actualrow.find(':checkbox:checked');
console.log($checkbox);
});
Use this instead:
$('#save').click(function () {
$('#mytable').find('input[type="checkbox"]:checked') //...
});
Let me explain you what the selector does:
input[type="checkbox"] means that this will match each <input /> with type attribute type equals to checkbox
After that: :checked will match all checked checkboxes.
You can loop over these checkboxes with:
$('#save').click(function () {
$('#mytable').find('input[type="checkbox"]:checked').each(function () {
//this is the current checkbox
});
});
Here is demo in JSFiddle.
And here is a demo which solves exactly your problem http://jsfiddle.net/DuE8K/1/.
$('#save').click(function () {
$('#mytable').find('tr').each(function () {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked') &&
row.find('textarea').val().length <= 0) {
alert('You must fill the text area!');
}
});
});
use .filter(':has(:checkbox:checked)' ie:
$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
$('#out').append(this.id);
});
The following code snippet enables/disables a button depending on whether at least one checkbox on the page has been checked.
$('input[type=checkbox]').change(function () {
$('#test > tbody tr').each(function () {
if ($('input[type=checkbox]').is(':checked')) {
$('#btnexcellSelect').removeAttr('disabled');
} else {
$('#btnexcellSelect').attr('disabled', 'disabled');
}
if ($(this).is(':checked')){
console.log( $(this).attr('id'));
}else{
console.log($(this).attr('id'));
}
});
});
Here is demo in JSFiddle.
I have a form which allows the user to add a new table row via a button in the bottom row which all is working well and also allows users to delete a table row but will always leave one row visible. You can see a working example of this at this jsFiddle.
I now need to make one change to how the Delete button appears. Currently it doesn't appear when there is one row, but when you add a row it appears for all rows except the last row. I need to change it using the following rules:
(i) if there is only one row the delete button should not appear
(ii) if there are 2 rows the delete button should appear on all rows, but if one row is delete rule (i) applies and there should be no delete button again
(iii) if there are 3 rows the delete button should appear on all rows, but if they delete 2 rows then rule (i) applies
and so on.
I'm hiding the delete button on the first row as follows:
<td>
<input type="button" class="button mt5 delbtn" value="Delete" id="deleteRowButton" name="deleteRowButton" style="display: none"/>
</td>
and here's the script that runs when new rows are added/deleted:
$('#lastYear').on('click', '.delbtn', function () {
$(this).closest('tr').remove()
});
var newIDSuffix = 2;
$('#lastYear').on('click', '.addbtn', function () {
var thisRow = $(this).closest('tr')[0];
$(thisRow).find('.delbtn').show();
var cloned = $(thisRow).clone();
cloned.find('input, select').each(function () {
var id = $(this).attr('id');
id = id.substring(0, id.length - 1) + newIDSuffix;
$(this).attr('id', id);
});
cloned.insertAfter(thisRow).find('input:text').val('');
cloned.find('.delbtn').hide();
cloned.find("[id^=lastYearSelect]")
.autocomplete({
source: availableTags,
select: function (e, ui) {
$(e.target).val(ui.item.value);
setDropDown.call($(e.target));
}
}).change(setDropDown);
$(this).remove();
newIDSuffix++;
});
I'm completely stumped at this point - appreciate any solutions to this problem. Thanks!
Hi i have updated your code. Now its working at fiddle.
$('#lastYear').on('click', '.delbtn', function () {
var tableRef=$(this).parent("td").parent("tr").parent("tbody");
$(this).closest('tr').remove();
if( tableRef.find("tr").length==3){
tableRef.find("tr").find("input.addbtn").show();
tableRef.find("tr").find("input.delbtn").hide();
}else{
tableRef.find("tr:last").find("input.addbtn").show();
}
});
var newIDSuffix = 2;
$('#lastYear').on('click', '.addbtn', function () {
var thisRow = $(this).closest('tr')[0];
$(thisRow).find('.delbtn').show();
var cloned = $(thisRow).clone();
cloned.find('input, select').each(function () {
var id = $(this).attr('id');
id = id.substring(0, id.length - 1) + newIDSuffix;
$(this).attr('id', id);
});
cloned.insertAfter(thisRow).find('input:text').val('');
cloned.find('.delbtn').show();
cloned.find("[id^=lastYearSelect]")
.autocomplete({
source: availableTags,
select: function (e, ui) {
$(e.target).val(ui.item.value);
setDropDown.call($(e.target));
}
}).change(setDropDown);
$(this).hide();
newIDSuffix++;
});
Please have a look at http://jsfiddle.net/wnSfa/7/
This will apply the 3 rules told by you.
I did changes in
$('#lastYear').on('click', '.delbtn', function () {
$(this).closest('tr').remove();
if ($("#lastYear tr").length < 4){
$('.delbtn').hide();
}
});
cloned.insertAfter(thisRow).find('input:text').val('');
if ($("#lastYear tr").length < 2){
cloned.find('.delbtn').hide();
}
Note: But if you delete the "last row" Which has "Add another activity" button, you can't add any other rows. You didn't mention user can delete the last or not so i didn't do anything for that. Let me know your comments.