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());
Related
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 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
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>
scope.routeToTxn = function(){
route.reload();
location.path('/tellers/' + routeParams.tellerId + "/cashiers/" + routeParams.cashierId +"/txns/" + scope.formData.currencyCode);
return function( item, startdate,enddate ) {
var filtered = [];
var txnstartDate = Date.parse(txnstartDate);
var txnendDate = Date.parse(txnendDate);
angular.forEach(item, function(item) {
if(item.completed_date > txnstartDate && item.completed_date < txnendDate) {
filtered.push(item);
}
});
return filtered;
};
};
<td class="col-md-2">
from date:
<input id="startDate" sort type="text" datepicker-pop="dd MMMM yyyy" ng-model="txnstartDate" class="form-control" is-open="opened" min="minDate" max="restrictDate"/>
</td>
<td class="col-md-2">
To date:
<input id="endDate" sort type="text" datepicker-pop="dd MMMM yyyy" ng-model="txnendDate" class="form-control" is-open="opened" min="minDate" max="restrictDate"/>
</td>
<td>
<a ng-click="routeToTxn()" class="btn btn-primary">{{'label.button.cashier.showtxn' | translate}} </a>
</td>
after clicking on search button the data should be filtered via 2 dates :
there are two insert boxes which will take 2 dates starting date and end date and after clicking on search box the data filtered data should be seen
Check at this snippet you probably want to format those dates so when you compare them they actually compare
https://jsfiddle.net/Lt7aP/14764/
formater used from this answer
https://stackoverflow.com/a/29774197/8101253
html
<div ng-app ng-controller="Ctrl">
<input ng-model="date1" type="date"></input>
<input ng-model="date2" type="date"></input>
<input type="submit" ng-click="compare(date1, date2)"></input>
{{array}}
</div>
javascript
function Ctrl($scope) {
$scope.array = [new Date("2018-11-06").toISOString().split('T')[0],
new Date("2018-11-07").toISOString().split('T')[0],
new Date("2018-11-09").toISOString().split('T')[0]
];
$scope.compare = function(date1, date2) {
$scope.array
.filter(x => {
console.log(x, date1, date2)
return x > date1 && x < date2
})
.forEach(x => console.log(x));
};
}
I have a text field which need to allow only numbers and decimals by user.
And also need to set minimum and maximum value.
<td ng-class="{ 'has-error' : eForm.marks_{{$index}}.$dirty && eForm.marks_{{$index}}.$error.required }">
<input type="text" name="marks_{{$index}}" ng-model="data.marks" placeholder="% of Marks" ng-pattern="/^[0-9]+([,.][0-9]+)?$/" class="form-control" ng-disabled="!eEditMode[$index]" min="1" max="100" ng-required="true">
<span ng-show="eForm.marks_{{$index}}.$dirty && eForm.marks_{{$index}}.$error.required" class="help-block">Marks is required</span>
</td>
You can use the number input:
<input type="number" name="input" ng-model="example.value"
min="0" max="99" required>
For more details: input components in ng / input[number]
This works for me:
Controller :
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
});
app.directive("marksRegex", function() {
var regexp;
return {
restrict: "A",
link: function(scope, elem, attrs) {
regexp = /^([0-9]([0-9]([\.]([0-9]([0-9]?)?)?)?)?)?$/;
var char;
elem.bind("keypress", function(event) {
if (event.which == 8) return;
char = String.fromCharCode(event.which);
if (!regexp.test(elem.val() + char))
event.preventDefault();
})
}
}
});
HTML :
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MainCtrl">
<label>Marks %:</label>
<input type="text" marks-regex>
</div>
</div>