I have a table where I can add multiple numbers and create an add more button also to add a new row on the table and calculate all total using jQuery. Now when I remove the new row, the total value is not updated, but when I click some of the input fields and then it is updated. Now my question is
How can I make the total value auto-update when the row is removed.
Below is my code:
function addMore() {
var new_raw = $('<tr><td>Remove<td><input type="number" class="addData"></td></tr>');
new_raw.insertBefore('#my_new_raw');
$("#myTable").on('click', '.remove', function() {
$(this).parent().parent().remove();
});
}
$(document).on('blur keyup', '.addData', function(e) {
var sum = 0;
$('.addData').each(function(i) {
if (!isNaN(this.value) && this.value.length != 0) {
if ($(this).hasClass('addData')) {
sum += parseFloat(this.value);
}
}
});
$('#my_total').val(sum.toFixed(2));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table" id="myTable">
<tbody>
<tr>
<td>Value 1</td>
<td><input type="number" class="addData"></td>
</tr>
<tr>
<td>Value 2</td>
<td><input type="number" class="addData"></td>
</tr>
<tr id="my_new_raw">
<td>Add More</td>
<td></td>
</tr>
<tr>
<td>Total</td>
<td><input type="number" readonly id="my_total"></td>
</tr>
</tbody>
</table>
I know I didn't call a function to update the total, because I don't know how. Help me here. Thanks for advance
TL;DR Simply calculate again.
Your calculate way is already good, just wrap it with a function, and then you can call it whenever you want to.
function addMore() {
var new_raw = $('<tr><td>Remove<td><input type="number" class="addData"></td></tr>');
new_raw.insertBefore('#my_new_raw');
$("#myTable").on('click', '.remove', function() {
$(this).parent().parent().remove();
calculate();
});
}
function calculate() {
var sum = 0;
$('.addData').each(function(i) {
if (!isNaN(this.value) && this.value.length != 0) {
if ($(this).hasClass('addData')) {
sum += parseFloat(this.value);
}
}
});
$('#my_total').val(sum.toFixed(2));
}
$(document).on('blur keyup', '.addData', function(e) {
calculate();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table" id="myTable">
<tbody>
<tr>
<td>Value 1</td>
<td><input type="number" class="addData"></td>
</tr>
<tr>
<td>Value 2</td>
<td><input type="number" class="addData"></td>
</tr>
<tr id="my_new_raw">
<td>Add More</td>
<td></td>
</tr>
<tr>
<td>Total</td>
<td><input type="number" readonly id="my_total"></td>
</tr>
</tbody>
</table>
If you use blur and keyup, the total will not be changed when changing the number value with arrow. I prefer input event instead. You can trigger the input event when clicking on Remove:
$('.addData').trigger('input');
Working Code Example:
function addMore() {
var new_raw = $('<tr><td>Remove<td><input type="number" class="addData"></td></tr>');
new_raw.insertBefore('#my_new_raw');
$("#myTable").on('click', '.remove', function() {
$(this).parent().parent().remove();
$('.addData').trigger('input');
});
}
$(document).on('input', '.addData', function(e) {
var sum = 0;
$('.addData').each(function(i) {
if (!isNaN(this.value) && this.value.length != 0) {
if ($(this).hasClass('addData')) {
sum += parseFloat(this.value);
}
}
});
$('#my_total').val(sum.toFixed(2));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table" id="myTable">
<tbody>
<tr>
<td>Value 1</td>
<td><input type="number" class="addData"></td>
</tr>
<tr>
<td>Value 2</td>
<td><input type="number" class="addData"></td>
</tr>
<tr id="my_new_raw">
<td>Add More</td>
<td></td>
</tr>
<tr>
<td>Total</td>
<td><input type="number" readonly id="my_total"></td>
</tr>
</tbody>
</table>
OR: By using a function
function addMore() {
var new_raw = $('<tr><td>Remove<td><input type="number" class="addData"></td></tr>');
new_raw.insertBefore('#my_new_raw');
$("#myTable").on('click', '.remove', function() {
$(this).parent().parent().remove();
updateTotal();
});
}
$(document).on('input', '.addData', function(e) {
updateTotal();
});
function updateTotal(){
var sum = 0;
$('.addData').each(function(i) {
if (!isNaN(this.value) && this.value.length != 0) {
if ($(this).hasClass('addData')) {
sum += parseFloat(this.value);
}
}
});
$('#my_total').val(sum.toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table" id="myTable">
<tbody>
<tr>
<td>Value 1</td>
<td><input type="number" class="addData"></td>
</tr>
<tr>
<td>Value 2</td>
<td><input type="number" class="addData"></td>
</tr>
<tr id="my_new_raw">
<td>Add More</td>
<td></td>
</tr>
<tr>
<td>Total</td>
<td><input type="number" readonly id="my_total"></td>
</tr>
</tbody>
</table>
Simple wrap the calculate code as function .And use closest() instead of parent().parent()
function addMore() {
var new_raw = $('<tr><td>Remove<td><input type="number" class="addData"></td></tr>');
new_raw.insertBefore('#my_new_raw');
}
function calc() {
var sum = 0;
$('.addData').each(function(i) {
if (!isNaN(this.value) && this.value.length != 0) {
if ($(this).hasClass('addData')) {
sum += parseFloat(this.value);
}
}
});
$('#my_total').val(sum.toFixed(2));
}
$(document).on('blur keyup', '.addData', function(e) {
calc();
}).on('click', '#myTable .remove', function() {
$(this).closest('tr').remove();
calc();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table" id="myTable">
<tbody>
<tr>
<td>Value 1</td>
<td><input type="number" class="addData"></td>
</tr>
<tr>
<td>Value 2</td>
<td><input type="number" class="addData"></td>
</tr>
<tr id="my_new_raw">
<td>Add More</td>
<td></td>
</tr>
<tr>
<td>Total</td>
<td><input type="number" readonly id="my_total"></td>
</tr>
</tbody>
</table>
<script>
function addMore() {
var new_raw = $('<tr><td>Remove<td><input type="number" class="addData"></td></tr>');
new_raw.insertBefore('#my_new_raw');
$("#myTable").on('click', '.remove', function () {
$(this).parent().parent().remove();
var sum = 0;
$('.addData').each(function (i) {
if (!isNaN(this.value) && this.value.length != 0) {
if ($(this).hasClass('addData')) {
sum += parseFloat(this.value);
}
}
});
$('#my_total').val(sum.toFixed(2));
});
}
$(document).on('blur keyup', '.addData', function (e) {
var sum = 0;
$('.addData').each(function (i) {
if (!isNaN(this.value) && this.value.length != 0) {
if ($(this).hasClass('addData')) {
sum += parseFloat(this.value);
}
}
});
$('#my_total').val(sum.toFixed(2));
})
</script>
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I have a problem here, that when I click the copy button on the recently copied row. It doesnt work. You guys know how to fix this?
This is my code
var controller = function(num1) {
$('#copy-' + num1).click(function() {
var $tableBody = $('#table_name').find("tbody"),
$trLast = $tableBody.find("#tr-" + num1),
$trNew = $trLast.clone();
// $trNew.find('input').val('');
$trLast.after($trNew);
console.clear()
// refresh_index();
});
}
function refresh_index() {
$('#table_name > tbody > tr').each(function(i) {
i++;
var select = $(this).find('select');
var text = $(this).find('input');
var button = $(this).find('button');
controller(i);
});
}
refresh_index();
This is my code in JSFIDDLE
To attach the click event on dynamically created element use the delegation approach using .on(). This will allow the event to work on the elements those are added in the body at a later time.
Change
$('#copy-' + num1).click(function() {
To
$('body').on('click','#copy-'+num1, function() {
$(function(){
var controller = function(num1){
$('body').on('click','#copy-'+num1, function() {
var $tableBody = $('#table_name').find("tbody"),
$trLast = $tableBody.find("#tr-"+num1),
$trNew = $trLast.clone();
// $trNew.find('input').val('');
$trLast.after($trNew);
console.clear()
// refresh_index();
});
}
function refresh_index(){
$('#table_name > tbody > tr').each(function (i) {
i++;
var select = $(this).find('select');
var text = $(this).find('input');
var button = $(this).find('button');
controller(i);
});
}
refresh_index();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table_name">
<thead>
<tr>
<th>No</th>
<th>Item</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr class="trs" id="tr-1">
<td>1</td>
<td>Mouse</td>
<td><button class="copy" id="copy-1">Copy</button></td>
</tr>
<tr class="trs" id="tr-2">
<td>2</td>
<td>Keyboard</td>
<td><button class="copy" id="copy-2">Copy</button></td>
</tr>
<tr class="trs" id="tr-3">
<td>3</td>
<td>Monitor</td>
<td><button class="copy" id="copy-3">Copy</button></td>
</tr>
</tbody>
</table>
You are adding it after the dom is loaded so it will not find it. If you use the on function to target something that was in the dom before it was dynamically added then add the target in the second variable after "click" then it should work.
$(function(){
var controller = function(num1){
var newThingy = '#copy-' + num1;
$("#table_name").on("click", newThingy, function() {
var $tableBody = $('#table_name').find("tbody"),
$trLast = $tableBody.find("#tr-"+num1),
$trNew = $trLast.clone();
// $trNew.find('input').val('');
$trLast.after($trNew);
console.clear()
// refresh_index();
});
}
function refresh_index(){
$('#table_name > tbody > tr').each(function (i) {
i++;
var select = $(this).find('select');
var text = $(this).find('input');
var button = $(this).find('button');
controller(i);
});
}
refresh_index();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table id="table_name">
<thead>
<tr>
<th>No</th>
<th>Item</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr class="trs" id="tr-1">
<td>1</td>
<td>Mouse</td>
<td><button class="copy" id="copy-1">Copy</button></td>
</tr>
<tr class="trs" id="tr-2">
<td>2</td>
<td>Keyboard</td>
<td><button class="copy" id="copy-2">Copy</button></td>
</tr>
<tr class="trs" id="tr-3">
<td>3</td>
<td>Monitor</td>
<td><button class="copy" id="copy-3">Copy</button></td>
</tr>
</tbody>
</table>
Use delegate event like $tableBody.find('.copy').off('click').on('click',function(){}); and bind click event after cloning the tr better to use class instead of ids. Here is the updated code based on your jsfiddle.
var $tableBody = $('#table_name').find("tbody");
clickEvent();
function clickEvent(){
$tableBody.find('.copy').off('click').on('click',function() {
$trLast = $(this).closest('tr'),
$trNew = $trLast.clone();
$trLast.after($trNew);
clickEvent();
});
function refresh_index(){
$('#table_name > tbody > tr').each(function (i) {
i++;
var select = $(this).find('td').eq(0).text(i);
});
}
refresh_index();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table_name">
<thead>
<tr>
<th>No</th>
<th>Item</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr class="trs" id="tr-1">
<td>1</td>
<td>Mouse</td>
<td><button class="copy" id="copy-1">Copy</button></td>
</tr>
<tr class="trs" id="tr-2">
<td>2</td>
<td>Keyboard</td>
<td><button class="copy" id="copy-2">Copy</button></td>
</tr>
<tr class="trs" id="tr-3">
<td>3</td>
<td>Monitor</td>
<td><button class="copy" id="copy-3">Copy</button></td>
</tr>
</tbody>
</table>
I have a problem here that when I click copy row and I want to get the remaining qty per item, the result is not accurate.
So let's just say the item mouse has 100 qty, and I inputted new qty for 50. So the remaining should be 50. And when I copied the item mouse and inputted 40, so the remaining now is 10. Same goes for other items. This should be the expected output.
Current Situation
JSFIDDLE
$('.qty').on("keyup", function() {
var id = $(this).data('id');
var value = $(this).val();
var sum = 0;
$("#table_name .qty").filter(function(){
if ($(this).data("id") == id){
sum += parseFloat(value);
}
});
console.log(sum);
$('.remaining').val(sum);
});
Your overall logic is REALLY unclear. Here is an example that might help.
$(function() {
function refreshIndex($t) {
$('tbody tr', $t).each(function(i, el) {
var c = i + 1;
var select = $(this).find('td:eq(0)').text(c);
});
}
function copyRow(e) {
var self = $(e.target);
var row = self.closest("tr");
row.clone().appendTo(self.closest("tbody"));
refreshIndex($("#table_name"));
}
function updateItem(e) {
var self = $(e.target);
var row = self.closest("tr");
var p = parseInt(self.val());
var q = parseInt(row.find("td:eq(2) input").val());
$('.remaining', row).val(q - p);
}
$("#table_name tbody").on("keyup", '.price', updateItem);
$("#table_name tbody").on('click', '.copy', copyRow);
});
#table_name tr td input {
width: 4em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table_name">
<thead>
<tr>
<th>No</th>
<th>Item</th>
<th>Total</th>
<th>Qnty</th>
<th>Action</th>
<th>Remaing</th>
</tr>
</thead>
<tbody>
<tr class="trs" id="tr-1">
<td>1</td>
<td>Mouse</td>
<td><input type="text" value="100" readonly></td>
<td><input type="text" class="price" data-id="79"></td>
<td><button class="copy" id="copy-1">Copy</button></td>
<td><input type="text" class="remaining"></td>
</tr>
<tr class="trs" id="tr-2">
<td>2</td>
<td>Keyboard</td>
<td><input type="text" value="20" readonly></td>
<td><input type="text" class="price" data-id="80"></td>
<td><button class="copy" id="copy-2">Copy</button></td>
<td><input type="text" class="remaining"></td>
</tr>
<tr class="trs" id="tr-3">
<td>3</td>
<td>Monitor</td>
<td><input type="text" value="50" readonly></td>
<td><input type="text" class="price" data-id="81"></td>
<td><button class="copy" id="copy-3">Copy</button></td>
<td><input type="text" class="remaining"></td>
</tr>
</tbody>
</table>
When I enter 40 under Price, 60 appears as the difference between the Quantity and the Amount entered.
When Copy is clicked, a new row is appended, and functionality is binded to it already due to use of .on().
Hope that helps.
Basically you can use the data-id attribute to target the rows you actually want to update.
var clone_controll = function(num) {
//Needed to mod this so add rows have the event handler
$('#table_name').on("keyup", ".qty", function() {
var id = $(this).data('id');
var value = $(this).val();
var sum = 0;
//Filter is the wrong choice here - it is designed to filter objects
/*$("#table_name .qty").filter(function(){
if ($(this).data("id") == id){
//I think this logic is incorrect as well
//You are only getting the value from the
//field you are typing in
sum += parseFloat(value);
}
});*/
/*Use a better selector with each()*/
$("#table_name [data-id=" + id +"]").each(function(){
//In this context "this" is the item iterated in "each"
sum += parseFloat($(this).val());
console.log(sum);
});
console.log("Final: " + sum);
//Here is your problem, this updates All "remaining fields
//$('.remaining').val(sum);
//All rows contiaining this data id
var relevantRows = $("[data-id=" + id + "]").closest("tr");
//Update the "remaining fields in those rows
$(relevantRows).find(".remaining").val(sum);
});
}
clone_controll();
var $tableBody = $('#table_name').find("tbody");
clickEvent();
function clickEvent(){
$tableBody.find('.copy').off('click').on('click',function() {
$trLast = $(this).closest('tr'),
$trNew = $trLast.clone();
$trLast.after($trNew);
clickEvent();
clone_controll();
});
function refresh_index(){
$('#table_name > tbody > tr').each(function (i) {
i++;
var select = $(this).find('td').eq(0).text(i);
});
}
refresh_index();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table id="table_name">
<thead>
<tr>
<th>No</th>
<th>Item</th>
<th>Qty</th>
<th>Your Qty</th>
<th>Action</th>
<th>Remaing per item(not per row)</th>
</tr>
</thead>
<tbody>
<tr class="trs" id="tr-1">
<td>1</td>
<td>Mouse</td>
<td><input type="text" value="100" readonly></td>
<td><input type="text" class="qty" data-id="79"></td>
<td><button class="copy" id="copy-1">Copy</button></td>
<td><input type="text" class="remaining"></td>
</tr>
<tr class="trs" id="tr-2">
<td>2</td>
<td>Keyboard</td>
<td><input type="text" value="20" readonly></td>
<td><input type="text" class="qty" data-id="80"></td>
<td><button class="copy" id="copy-2">Copy</button></td>
<td><input type="text" class="remaining"></td>
</tr>
<tr class="trs" id="tr-3">
<td>3</td>
<td>Monitor</td>
<td><input type="text" value="50" readonly></td>
<td><input type="text" class="qty" data-id="81"></td>
<td><button class="copy" id="copy-3">Copy</button></td>
<td><input type="text" class="remaining"></td>
</tr>
</tbody>
</table>
Your logic is still pretty unclear, but hopefully this gets you moving in the right direction.
Edit
So many good answers and all of them work! Thanks a lot guys :) I wish I could mark all of them as solved!
----
Good day
Let's say I have these 2 text inputs:
<input type="text" id="plt_quantity_sum"/> <!-- this should calculate the "#quantity" where each "#uom_value" is "PLT" -->
<input type="text" id="crt_quantity_sum"/><!-- this should calculate the "#quantity" where each "#uom_value" is "CRT" -->
Let's assume the following scenario:
<table>
<tbody>
<tr>
<th>Item Name</th>
<th id="uom_value">UOM</th>
<th id="qty">Quantity</th>
</tr>
<tr>
<td>Item 1</td>
<td id="uom_value">PLT</td>
<td id="qty">5</td>
</tr>
<tr>
<td>Item 2</td>
<td class="uom_value">PLT</td>
<td id="qty">3</td>
</tr>
<tr>
<td>Item 3</td>
<td id="uom_value">CRT</td>
<td id="qty">2</td>
</tr>
<tr>
<td>Item 4</td>
<td id="uom_value">CRT</td>
<td id="qty">3</td>
</tr>
</tbody>
</table>
<input type="text" id="plt_quantity_sum" />
<input type="text" id="crt_quantity_sum" />
What needs to happen:
When the document loads, or via a button click; the quantity of "#plt_quantity_sum" and "#crt_quantity_sum" should be calculated based on their respective quantities and "UOM" values.
Some Javascript I had in mind which should clarify what exactly needs to happen:
$(document).ready(function(){
if (document.getElementById("#uom_value").value == "PLT"){
document.getElementById("#plt_quantity_sum").value == (sum of #qty);
}
else if (document.getElementById("#uom_value").value == "CRT"){
document.getElementById("#crt_quantity_sum").value == (sum of #qty);
}
});
Thanks for reading and I would greatly appreciate any help.
You just need declare two variables crtQtySum and pltQtySum for the two sums and initialize them to 0, then loop over the tds and check if it's crt or plt and updtae your variables accordingly:
$(document).ready(function() {
var crtQtySum = 0;
var pltQtySum = 0;
$(".uom_value").each(function() {
if ($(this).text() === "CRT") {
crtQtySum += parseInt($(this).next("td.qty").text());
} else if ($(this).text() === "PLT") {
pltQtySum += parseInt($(this).next("td.qty").text());
}
});
$("#plt_quantity_sum").val(pltQtySum);
$("#crt_quantity_sum").val(crtQtySum);
});
$(document).ready(function() {
var crtQtySum = 0;
var pltQtySum = 0;
$(".uom_value").each(function() {
if ($(this).text() === "CRT") {
crtQtySum += parseInt($(this).next("td.qty").text());
} else if ($(this).text() === "PLT") {
pltQtySum += parseInt($(this).next("td.qty").text());
}
});
$("#plt_quantity_sum").val(pltQtySum);
$("#crt_quantity_sum").val(crtQtySum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th>Item Name</th>
<th class="uom_value">UOM</th>
<th class="qty">Quantity</th>
</tr>
<tr>
<td>Item 1</td>
<td class="uom_value">PLT</td>
<td class="qty">5</td>
</tr>
<tr>
<td>Item 2</td>
<td class="uom_value">PLT</td>
<td class="qty">3</td>
</tr>
<tr>
<td>Item 3</td>
<td class="uom_value">CRT</td>
<td class="qty">2</td>
</tr>
<tr>
<td>Item 4</td>
<td class="uom_value">CRT</td>
<td class="qty">3</td>
</tr>
</tbody>
</table>
PLT:<input type="text" id="plt_quantity_sum" readonly/></br>
CRT:<input type="text" id="crt_quantity_sum" readonly/>
Note:
I used readonly attribute with the inputs, as they're just used to display the sums so they can't be modified, but we could just used a block element for that like div or span.
You can try this code. I ve didnt test it.
var plt_count = 0;
var crt_count = 0;
$(".uom_value").each(function() {
if($(this).html === 'PLT'){
plt_count += parseInt($(this).closest('.qty').html());
}
if($(this).html === 'CRT'){
crt_count += parseInt($(this).closest('.qty').html());
}
});
$("#plt_quantity_sum").val(plt_count);
$("#crt_quantity_sum").val(crt_count);
Apart from correcting the spelling mistakes that Hamza pointed out, I'd say you should basically iterate through the elements given its class name document.getElementsByClassName('.someclass') and then store and sum the value of each one of its siblings with class '.qty'.
Then you take that value and use it to populate the input you want.
Hope that helps ;)
This can be done using so many method, this is one of them :
$(document).ready(function(){
var sum_PLT = 0, sum_CRT = 0;
$('table > tbody > tr').each(function() {
tr = $(this)[0];
cells = tr.cells;
if(cells[0].textContent != "Item Name"){//To exclude the <th>
if(cells[1].textContent == "PLT")
sum_PLT += parseInt(cells[2].textContent);
else
sum_CRT += parseInt(cells[2].textContent);
}
});
$("#plt_quantity_sum").val(sum_PLT);
$("#crt_quantity_sum").val(sum_CRT);
});
This is a working jsFiddle.
You might want to try this code.
<script>
$(document).ready(function(){
var plt_qty = 0;
var crt_qty = 0;
$('.uom_value').each(function(){
if ($(this).text() === 'PLT' ) {
plt_qty = plt_qty + parseInt($(this).parent().find('.qty').text());
}else if ($(this).text() === 'CRT' ) {
crt_qty = crt_qty + parseInt($(this).parent().find('.qty').text());
}
});
$("#plt_quantity_sum").val(plt_qty);
$("#crt_quantity_sum").val(crt_qty);
});
</script>
Note : remove class uom_value in <th class="uom_value">UOM</th>.
I have a table with some row colored as green.Each row have a checkbox.
When I click submit button i need to validate that only green colored row whose checkboxes are not checked should be checked.
No other colored rows and just the green one(#47A347).
Below is my html.Can anyone help me getting the solution.
<form method="post" action="test2.html">
<table>
<tr bgcolor="#47A347" class="rowb">
<td>Hello</td>
<td><input type="checkbox" id="chk" class="linebox"></td>
</tr>
<tr bgcolor="#47A347" class="rowb">
<td>Hello 1</td>
<td><input type="checkbox" id="chk1" class="linebox"></td>
</tr>
<tr class="rowb">
<td>Hello 2</td>
<td><input type="checkbox" id="chk1" class=""></td>
</tr>
<tr>
<td><input type="submit" id="btn" value="Submit"></td>
</tr>
</table>
</form>
I have tried below jquery code.Though it works it fails sometimes.
<script>
jQuery(document).on('click', '#btn', function (event)
{
var rv = true;
$(".rowb").each(function()
{
if($(this).css("background-color") == "rgb(71, 163, 71)")
{
var ischk = 0;
var row = $(this);
if (row.find('input[class="linebox"]').is(':checked') )
{
ischk++;
}
if(ischk==0)
{
rv=false;
}
}
});
if (!rv)
{
alert('Please check');
event.preventDefault();
}
});
</script>
Try this snippet. Should give you an alert for each green checkbox that has not been checked on click of the submit 'btn'. If there is a green row checkbox that has not been checked, the default submit action will be stopped.
$(document).ready(function(){
$('#btn').on('click', function(){
var i = 1;
var error = false;
$(".rowb").each(function() {
ischk = 0;
if($(this).attr("bgcolor") == "#47A347") {
if (!$(this).find('input.linebox').is(':checked') )
{
alert('Please check green checkbox #' + i);
error = true;
}
i++;
}
});
if (error){
event.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form method="post" action="test2.html">
<table>
<tr bgcolor="#47A347" class="rowb">
<td>Hello</td>
<td><input type="checkbox" id="chk" class="linebox"></td>
</tr>
<tr bgcolor="#47A347" class="rowb">
<td>Hello 1</td>
<td><input type="checkbox" id="chk1" class="linebox"></td>
</tr>
<tr class="rowb">
<td>Hello 2</td>
<td><input type="checkbox" id="chk1" class=""></td>
</tr>
<tr>
<td><input type="submit" id="btn" value="Submit"></td>
</tr>
</table>
</form>
Instead of asserting in background-color try checking for bgcolor attribute.
//if($(this).css("background-color") == "rgb(71, 163, 71)")
if( $(this).attr("bgcolor") == "#47A347" )
Here's the full refactored code:
jQuery(document).on('click', '#btn', function (event)
{
var rv = true;
$(".rowb").each(function()
{
if($(this).attr("bgcolor") == "#47A347")
{
if ( !$(this).find('.linebox').is(':checked') )
{
rv = false;
return false
}
}
});
if (!rv)
{
alert('Please check');
event.preventDefault();
}
});
$('#btn').on('click', function(){
var data = {};
var form = $(this).closest('form');
$('[bgcolor="#47A347"]', form).each(function(){
data[this.id] = $(this).find('input').val();
})
});
Note: you didn't provide name attribute for inputs. With name attribute provided you can use jQuery's serialize method to gather form data automatically. To filter out unneeded fields you can temporarily set them to disabled state.
Any help would be greatly appreciated.
What I'm trying to achieve is when a number/text in input into the code box it searches the table, if found increments quantity by one, if not found adds a new row counting the no column by one.
I already a some basic jQuery code.
<input type="text" style="width: 200px" id="code" name="code" />
<input id = "btnSubmit" type="submit" value="Release"/>
<table> <thead>
<tr>
<th>No</th>
<th>Code</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>4444</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>5555</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>6666</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>7777</td>
<td>1</td>
</tr>
</tbody>
</table>
edit: my code.
$(document).ready(function() {
$("#btnSubmit").click(function() {
var code = $("input#code").val()
var table = $("table tbody");
table.find('tr').each(function(i) {
no = $(this).find('td').eq(0).text(),
productId = $(this).find('td').eq(1).text(),
Quantity = $(this).find('td').eq(2).text();
if (productId == code) { //see if product is in table
Quantity = +Quantity + +Quantity; // increase qty
alert('found' + Quantity);
} else {
// Add new row
alert('not found');
}
});
});
});
I put together a JSFiddle for you, and copied the JS code here. I tried to make it as beginner friendly as possible...
$("#btnSubmit").on("click", function(){
numRows = $("tr").length;
for(var i=1 ; i<numRows ; i++){
var code = $("tr:nth-child(" + i + ") td:nth-child(2)").html();
var qty = $("tr:nth-child(" + i + ") td:nth-child(3)").html();
if(code == $("#code").val()){
$("tr:nth-child(" + i + ") td:nth-child(3)").html(parseInt(qty) + 1);
return true;
}
}
$("tbody").append("<tr><td>" + numRows + "</td><td>" + $("#code").val() + "</td><td>1</td></tr>");
return true;
});
I have created a sample code using jQuery. It took me like 10 minutes to figure out what you are trying to achive but I hope I understood you quite well:
HTML Side:
<input type="text" style="width: 200px" id="code" name="code" />
<input id = "btnSubmit" type="submit" value="Release"/>
<table> <thead>
<tr>
<th>No</th>
<th>Code</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>4444</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>5555</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>6666</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>7777</td>
<td>1</td>
</tr>
</tbody>
</table>
and our JavaScript:
$(document).ready(function() {
var found = false;
$("input#btnSubmit").on("click", function() {
var search_val = $("input#code").val();
$("tr").each(function() {
var obj = $(this);
obj.find("td").each(function() {
if(parseInt($(this).html()) == parseInt(search_val))
{
obj.find("td:nth-of-type(3)").html(parseInt(obj.find("td:nth-of-type(3)").html()) + 1);
found = true;
}
});
})
if(found == false)
{
$("table").append("<tr><td>"+($("tr").length)+"</td><td>"+search_val+"</td><td>1</td></tr>");
}
found = false;
});
});
Here's JSFiddle: http://jsfiddle.net/f17gudfw/4/