Need to prevent the user from entering more than the existing quantity. It should check the total quantities entered on change event as well as on submit click.
For example, the first row(Part 1) has 50 quantities when the user is adding rows and the total quantities entered against "Part 1" should not exceed 50 and a text should display above the row. Any help would be appreciated.
HTML:
<form name="req" method="post">
<table id="exampleTbl">
<tr>
<td>Part 1</td>
<td><input type="number" name="quantity" value="50"></td>
<td>
<button type="button" class="addRow">+</button>
</td>
</tr>
<tr>
<td>Part 2</td>
<td><input type="number" name="quantity" value="100"></td>
<td>
<button type="button" class="addRow">+</button>
</td>
</tr>
</table>
<input type="submit" name="Submit" value="Submit">
</form>
Jquery:
$(function() {
$('#exampleTbl').delegate('button.addRow', 'click', function() {
var row = $(this).closest('tr'); // get the parent row of the clicked button
var html = $(this).closest('tr').clone();
$(html).insertAfter(row); // insert content
let btn = $('Remove');
btn.click(function () {
$(html).remove(); // Remove row on click
})
$(html).find('.addRow').replaceWith(btn);
});
});
In below code snippet i have given class to your trs to differentiate them with original quantity and the quantity which user can change . Also , whenever user will change input then we need find sum of all quantity of Part 1 or Part 2 .So , i have use tr class which will have either Part 1 or Part 2 to iterate over trs input .
Demo Code :
$(function() {
$('#exampleTbl').delegate('button.addRow', 'click', function() {
var row = $(this).closest('tr'); // get the parent row of the clicked button
var html = $(this).closest('tr').clone();
$(html).insertAfter(row); // insert content
let btn = $('Remove');
btn.click(function() {
$(html).remove(); // Remove row on click
})
$(html).find('.addRow').replaceWith(btn);
});
});
$(document).on("change", "input", function() {
var sum = 0;
$(".total_qty_entered").remove(); //remove div
var name = $(this).closest('tr').attr('class'); //get class
//get original quantity
var qty = $("." + name + "_original").find('td:eq(2)').text();
//loop through tr with same class > inputs
$("." + name + " input[name=quantity]").each(function() {
sum += +$(this).val();
});
console.log("Quantity : " + qty + " | Sum : " + sum)
if (sum > qty) {
$(this).before('<div class="alert alert-danger total_qty_entered" role="alert">Total Quantity should not exceed ' + qty + '</div>');
}
});
//call when on submit
function mySubmitFunction(e) {
//e.preventDefault();
var result = true;
$("tr[data-value ='original']").each(function() {
var name = $(this).find('td:eq(0)').text();
var qty = $(this).find('td:eq(2)').text();
var new_name = name.replace(/\s/g, '');
var sum = 0;
$("." + new_name + " input[name=quantity]").each(function() {
sum += +$(this).val();
});
console.log("Name : " +name+ " Sum : "+sum + " || Qty : " + qty)
if (sum > qty) {
//do something
alert("please check quanity is greater for "+name)
result = false;
}
});
return result;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="req" method="post" onsubmit="return mySubmitFunction(event)">
<table id="exampleTbl">
<!--added this class-->
<tr data-value="original" class="Part1_original">
<td>Part 1 </td>
<td>Original Quantity : </td>
<td>50</td>
</tr>
<!--added this class-->
<tr class="Part1">
<td>Part 1</td>
<td><input type="number" name="quantity" value="50"></td>
<td>
<button type="button" class="addRow">+</button>
</td>
</tr>
<tr data-value="original" class="Part2_original">
<td>Part 2</td>
<td>Original Quantity : </td>
<td>100</td>
</tr>
<tr class="Part2">
<td>Part 2</td>
<td><input type="number" name="quantity" value="100"></td>
<td>
<button type="button" class="addRow">+</button>
</td>
</tr>
</table>
<input type="submit" name="Submit" value="Submit">
</form>
Update 1 :
You can give class to your input so that it can use in each to iterate over the inputs having same class and check if against the total quantity .
Demo code :
$(function() {
$('#exampleTbl').delegate('button.addRow', 'click', function() {
var row = $(this).closest('tr'); // get the parent row of the clicked button
var html = $(this).closest('tr').clone();
$(html).insertAfter(row); // insert content
let btn = $('Remove');
btn.click(function() {
$(html).remove(); // Remove row on click
})
$(html).find('.addRow').replaceWith(btn);
});
});
$(document).on("change", "input", function() {
var sum = 0;
//get total quantity
var qty = $(this).closest('td').next('td').text(); //get class
var name = $(this).attr('class'); //get class
//loop through tr with same class > inputs
$("tr > td input[class=" + name + "]").each(function() {
sum += +$(this).val();
});
$(".total_qty_entered").remove(); //remove div
if (sum > qty) {
$(this).before('<div class="alert alert-danger total_qty_entered" role="alert">Total Quantity should not exceed ' + qty + '</div>');
}
});
//call when on submit
function mySubmitFunction(e) {
//e.preventDefault();
var result = true;
//loop through td input
$("tr > td input").each(function() {
var name = $(this).attr('class');
var qty = $(this).closest('td').next('td').text(); //get class
var sum = 0;
//iterate through all inputs with same class
$("." + name).each(function() {
sum += +$(this).val();
});
if (sum > qty) {
//do something
$(this).before('<div class="alert alert-danger total_qty_entered" role="alert">Total Quantity should not exceed ' + qty + '</div>');
result = false;
}
});
return result;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="req" method="post" onsubmit="return mySubmitFunction(event)">
<table id="exampleTbl">
<tr>
<td>Part 1</td>
<td><input type="number" name="quantity" value="50" class="Part1"></td>
<td>50</td>
<td>
<button type="button" class="addRow">+</button>
</td>
</tr>
<tr>
<td>Part 2</td>
<td><input type="number" name="quantity" value="100" class="Part2"></td>
<td>100</td>
<td>
<button type="button" class="addRow">+</button>
</td>
</tr>
</table>
<input type="submit" name="Submit" value="Submit">
</form>
Related
I'm tyring to display a "result table"(showing the area value and calculated time) only after a user inputs both width and height value and presse the button.
What I attempted was display input values on a sheet so the inputs are correctly passed to the function setParam().
My problems are
How to display a table only after a button is pressed.
How to set a calculated are value returned from a function to the web application.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div id="area">
<table>
<thead>
<tr>
<th>Area</th>
</tr>
</thead>
<tbody>
<tr>
<td>width</td>
<td><input id="width" type="number" ></input></td>
</tr>
<tr>
<td>height</td>
<td><input id="height" type="number"></input></td>
</tr>
</tbody>
</table>
</div>
<div>
<input type="button" onclick="calculateArea()" id="" value="Calcuate This!">
</div>
<div id="createdTable"></div>
<script>
function calculateArea() {
const width = document.getElementById('width').value;
const height = document.getElementById('height').value;
google.script.run.setParam(width, height);
var htmlTable = '<table id="xxx" border=1>' +
'<thead>' +
'<tr> +
'<th>Result</th> +
'</tr>' +
'</thead>' +
'<tbody>' +
'<tr>' +
'<td>Area</td>' +
'<td><input value=""><?=getArea();?></input></td>' +
'</tr>' +
'<tr>' +
'<td>Calculation Time</td>' +
'<td><input value=""></input></td>' +
'</tr>' +
'</tbody>' +
'</table>';
document.getElementById("createdTable").innerHTML = htmlTable;
}
</script>
</body>
</html>
let width = 0;
let height = 0;
let area = 0;
let time = 0;
function doGet() {
return HtmlService.createTemplateFromFile("index").evaluate();
}
function setParam(width, height) {
this.width = width;
this.height = height;
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/xxxx/edit#gid=0");
var ws = ss.getSheetByName("sheet1");
ws.getRange(1,1).setValue(width);
ws.getRange(2,1).setValue(height);
}
function getArea() {
area = width * height;
return area;
}
function getTime() {
return time;
}
I have below web page it shows I have created one table & added AddRow & remove row functions using jquery. I am calling JSP file through AJAX call for auto search.
But it seems working for only first row of table & when m searching in newly added row suggestions are showing in first row only.
Below is screenshot
$(document).ready(function() {
// Denotes total number of rows
var rowIdx = 0;
// jQuery button click event to add a row
$('#addBtn').on('click', function() {
// Adding a row inside the tbody.
$('#tbody').append(`
<tr id="R${++rowIdx}">
<td class="row-index text-center">
<p>Row ${rowIdx}</p>
</td>
<td class="cb"><input class="form-control" type="text" value="" id="inputString" name="inputString" />
<div id="showList">
<ul class="list-group"></ul>
</div>
</td>
<td>
<input type="checkbox" name="debit" class="form-control">
</td>
<td>
<input type="checkbox" name="credit"class="form-control">
</td>
<td>
<input type="number" name="amount" class="form-control">
</td>
<td class="text-center">
<button class="btn btn-danger remove" type="button">Remove</button>
</td>
</tr>`);
});
/*$("#tbody").on("keyup"," input[name^=inputString]", function(){
$("tbody tr").each(function () {
var search = $(this).closest('tr').find("td:eq(rowIdx) input").val();
if(search !='' && search !=null) {
$.ajax({
type:'POST',
url:'ledgers.jsp',
data:'key='+search,
success:function(data){
$('#showList').html(data);
}
});
}
else {
$('#showList').html('');
}
});
});*/
$("#tbody").on("keyup", " input[name^=inputString]", function() {
$("tbody tr").each(function() {
var search = $(this).closest('tr').find("input").val();
if (search != '' && search != null) {
$.ajax({
type: 'POST',
url: 'ledgers.jsp',
data: 'key=' + search,
success: function(data) {
$('#showList').html(data);
}
});
} else {
$('#showList').html('');
}
});
});
$("#tbody").on("click", "li", function() {
$('#inputString').val($(this).text());
$('#showList').html('');
});
// jQuery button click event to remove a row.
$('#tbody').on('click', '.remove', function() {
// Getting all the rows next to the row
// containing the clicked button
var child = $(this).closest('tr').nextAll();
// Iterating across all the rows
// obtained to change the index
child.each(function() {
// Getting <tr> id.
var id = $(this).attr('id');
// Getting the <p> inside the .row-index class.
var idx = $(this).children('.row-index').children('p');
// Gets the row number from <tr> id.
var dig = parseInt(id.substring(1));
// Modifying row index.
idx.html(`Row ${dig - 1}`);
// Modifying row id.
$(this).attr('id', `R${dig - 1}`);
});
// Removing the current row.
$(this).closest('tr').remove();
// Decreasing total number of rows by 1.
rowIdx--;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group required col-md-8">
<table class="table table-bordered" id="table_field">
<thead>
<tr id="r1">
<th>Row No</th>
<th>Ledger Name</th>
<th>Debit</th>
<th>Credit</th>
<th>Amount</th>
<th>Add or Remove</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
<tr>
<input class="btn btn-success" type="button" name="add" id="addBtn" value="Add">
</tr>
</table>
<center>
<input class="btn btn-success" type="submit" name="save" id="save" value="Save">
</center>
</div>
can anybody suggest me whats wrong with above code.
Run auto search for every table row TD input field
enter image description here
Please replace the keyup function() with below code:
$("#tbody").on("keyup", "input[name^=inputString]", function() {
var $this = $(this);
$("tbody tr").each(function() {
var search = $(this).closest('tr').find("input").val();
if (search != '' && search != null) {
$.ajax({
type: 'POST',
url: 'ledgers.jsp',
data: 'key=' + search,
success: function(data) {
$this.next('#showList').html(data);
}
});
} else {
$('#showList').html('');
}
});
});
Please let me know if you find any issues.
Thanks.
I'm trying to append multiple data (from date form) into table, using Jquery and MomentJS. But the result not showing what I want.
Here's my code :
$(".btnNext").on('click', function(e) {
var Day = 1;
var newDay = Day++;
var fromDate = $('#campaign_start_period_id').val(),
toDate = $('#campaign_end_period_id').val(),
from, to, druation;
from = moment(fromDate, 'YYYY-MM-DD');
to = moment(toDate, 'YYYY-MM-DD');
/* using diff */
duration = to.diff(from, 'days')
let date = [];
for (var m = moment(fromDate); m.isBefore(toDate); m.add(1, 'days')) {
date.push(m.format('MMM. DD, YYYY'));
}
var tr = '<tr class="v-middle">';
tr += '<td>' + newDay + '</td>';
tr += '<td class="text-color">' + date + '</td>';
tr += "</tr>";
$('#result tbody').append(tr);
});
<script src="https://unpkg.com/moment#2.10.6/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<input class="form-control" type="date" id="campaign_start_period_id" maxlength="None" name="campaign_start_period" placeholder="dd M yyyy" type="text" value="{{ campaign_start_period }}" />
<input class="form-control" type="date" id="campaign_start_period_id" maxlength="None" name="campaign_end_period" placeholder="dd M yyyy" type="text" value="{{ campaign_end_period }}" />
<button class="btnNext" value="" type="button">Next</button>
<table class="table toggle-circle table-hover table-striped" id="result">
<thead>
<tr>
<th>Days</th>
<th>Date</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
My code append "date" inside one "<tr><td></td></tr>" and not adding other "<tr></tr>".
What I expect is to show data like this :
You should iterate on the date array and add each date to a 'tr' tag
$(".btnNext").on('click', function(e) {
var Day = 1;
var newDay = Day++;
var fromDate = $('#campaign_start_period_id').val(),
toDate = $('#campaign_end_period_id').val(),
from, to, druation;
from = moment(fromDate, 'YYYY-MM-DD');
to = moment(toDate, 'YYYY-MM-DD');
/* using diff */
duration = to.diff(from, 'days')
let date = [];
for (var m = moment(fromDate); m.isBefore(toDate); m.add(1, 'days')) {
date.push(m.format('MMM. DD, YYYY'));
}
var tr = '';
date.forEach((newDay,index) => {
tr += '<tr class="v-middle">';
tr += '<td>' + (index + 1) + '</td>';
tr += '<td class="text-color">' + newDay + '</td>';
tr += "</tr>";
});
$('#result tbody').append(tr);
});
<script src="https://unpkg.com/moment#2.10.6/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<input class="form-control" type="date" id="campaign_start_period_id" maxlength="None" name="campaign_start_period" placeholder="dd M yyyy" type="text" value="{{ campaign_start_period }}" />
<input class="form-control" type="date" id="campaign_start_period_id" maxlength="None" name="campaign_end_period" placeholder="dd M yyyy" type="text" value="{{ campaign_end_period }}" />
<button class="btnNext" value="" type="button">Next</button>
<table class="table toggle-circle table-hover table-striped" id="result">
<thead>
<tr>
<th>Days</th>
<th>Date</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
I'm stuck in the jQuery code, I want to make dynamic fields, but the problem is when I want to print the following equation in the total value, it only appears in the first value of the dynamic values, what is the solution to this problem
<div class="container">
<table class="table table-responsive" id="tal">
<thead>
<tr>
<td>price</td>
<td>quantity</td>
<td>total $</td>
<td><button type="button" class="btn-outline-success" id="add-new-row">addRow</button></td>
</tr>
</thead>
<tbody id="addNewTR">
<tr>
</tr>
</tbody>
</table>
</div>
jquery code
$(document).ready(function(){
var x = 1;
var min = 1;
var max = 4;
var html = '<tr><td><input type="text" name="price[]" id="price" ></td><td><input type="text" name="qty[]" id="qty" ></td><td><input type="text" name="total[]" id="total" disabled=""></td><td><button type="button" class="btn-outline-danger" id="remove">remove</button></td></tr>';
$("#add-new-row").click(function(i){
i.preventDefault();
if (x <= max) {
var price = $("#price").val();
var qty = $("#qty").val();
var sum = parseInt($("#price").val()) * parseInt($("#qty").val()) ;
$("#total").val(sum);
$("#addNewTR").append(html);
x++;
}
});
$("#addNewTR").on('click','#remove',function(){
$(this).closest("tr").remove();
x--;
});
});
here is the updated working code. you must need a unique id for each append element.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var x = 1;
var min = 1;
var max = 4;
$("#add-new-row").click(function (i) {
i.preventDefault();
if (x <= max) {
var i = x - 1;
var price = $("#price" + i).val();
var qty = $("#qty" + i).val();
var sum = parseInt($("#price" + i).val()) * parseInt($("#qty" + i).val());
$("#total" + i).val(sum);
var html = "";
html = '<tr><td><input type="text" name="price[]" id="price' + x + '" ></td><td><input type="text" name="qty[]" id="qty' + x + '" ></td><td><input type="text" name="total[]" id="total' + x + '" disabled=""></td><td><button type="button" class="btn-outline-danger" id="remove">remove</button></td></tr>';
$("#addNewTR").append(html);
x++;
}
});
$("#addNewTR").on('click', '#remove', function () {
$(this).closest("tr").remove();
x--;
});
});
</script>
<body>
<div class="container">
<table class="table table-responsive" id="tal">
<thead>
<tr>
<td>price</td>
<td>quantity</td>
<td>total $</td>
<td><button type="button" class="btn-outline-success" id="add-new-row">addRow</button></td>
</tr>
</thead>
<tbody id="addNewTR">
<tr>
</tr>
</tbody>
</table>
</div>
<body/>
function fn_onblulr(e){
var price = $(e.target).closest('tr').find('.quantity').val();
let quantity = $(e.target).closest('tr').find('.quantity').val();
let total = $(e.target).closest('tr').find('.total');
$(total).val(price*quantity);
}
$(document).ready(function(){
var x = 1;
var min = 1;
var max = 4;
var html = '<tr><td><input type="text" class="price" name="price[]" id="price" ></td><td><input type="text" class="quantity" name="qty[]" onblur="fn_onblulr(event)" id="qty" ></td><td><input type="text" class="total" name="total[]" id="total" disabled=""></td><td><button type="button" class="btn-outline-danger" id="remove">remove</button></td></tr>';
$("#add-new-row").click(function(i){
i.preventDefault();
if (x <= max) {
var price = $("#price").val();
var qty = $("#qty").val();
var sum = parseInt($("#price").val()) * parseInt($("#qty").val()) ;
$("#total").val(sum);
$("#addNewTR").append(html);
x++;
}
});
$("#addNewTR").on('click','#remove',function(){
$(this).closest("tr").remove();
x--;
});
});
Change Script
i am newer in jquery And I have a problem in Multiply with jquery
my sample Form is :
The first line of the form is calculated correctly But multiplication is not done from the second line.
MyCode is :
$(document).ready(function () {
var rowIdx = 0;
$('#addBtn').on('click', function () {
$('#tbody').append(`<tr id="R${++rowIdx}">
<td>${rowIdx}</td>
<td>
<select id="group" name="group" class="form-control form-select">
#foreach($groups as $group)
<option>{{ $group->title }}</option>
#endforeach
</select>
</td>
<td><input type="number" name="number" id="a1"></td>
<td><input type="number" name="price" id="a2"></td>
<td><input type="number" name="total_price" id="a3"></td>
<td class="text-center">
<button class="btn btn-danger remove"
type="button">Remove</button>
</td>
</tr>`);
$('#a1').keyup(calculate);
$('#a2').keyup(calculate);
function calculate(e)
{
$('#a3').val($('#a1').val() * $('#a2').val());
}
});
$('#tbody').on('click', '.remove', function () {
var child = $(this).closest('tr').nextAll();
child.each(function () {
var id = $(this).attr('id');
var idx = $(this).children('.row-index').children('p');
var dig = parseInt(id.substring(1));
idx.html(`Row ${dig - 1}`);
$(this).attr('id', `${dig - 1}`);
});
$(this).closest('tr').remove();
rowIdx--;
});
});
You can use $(this).closest("tr") to get closest tr where keyup/change has been taken place then using same get required input values and add total to your total_price inputs .
Demo Code :
$(document).ready(function() {
var rowIdx = 0;
$('#addBtn').on('click', function() {
$('#tbody').append(`<tr id="R${++rowIdx}">
<td>${rowIdx}</td>
<td>
<select id="group" name="group" class="form-control form-select">
#foreach($groups as $group)
<option>{{ $group->title }}</option>
#endforeach
</select>
</td>
<td><input type="number" min ="0" value="0" name="number"></td>
<td><input type="number" min ="0" value="0" name="price"></td>
<td><input type="number"min ="0" value="0" name="total_price"></td>
<td class="text-center">
<button class="btn btn-danger remove"
type="button">Remove</button>
</td>
</tr>`);
});
//on key up or change
$(document).on("change keyup", "tbody input[type=number]", function() {
var qty = 0,
total = 0;
//get closest tr
var selector = $(this).closest("tr")
//get numer & price from same row
var number = parseInt(selector.find("[name=number]").val())
var price = parseInt(selector.find("[name=price]").val())
//add total in totalprice in same row
selector.find('[name=total_price]').val(number * price);
//loop thorugh each trs
$("#tbody tr").each(function() {
//add value of each inputs
qty += parseInt($(this).find("[name=number]").val())
total += parseInt($(this).find("[name=total_price]").val())
})
//add result in dom..
$("#qty").text(qty);
$("#total").text(total);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id="tbody"></tbody>
</table>
<button id="addBtn" type="button">Add</button> <br/>Total qty : <span id="qty"></span> <br/>Total price : <span id="total"></span>
Here is a version of selector that might work for you.
let parentTR = $(this).parents('tr')[0];
let resultInput = $(parentTR).find("#a3");
resultInput.val($(parentTR).find("#a1").val() * $(parentTR).find("#a2").val());