How to set the selected value of a dynamically created select box - javascript

I have a table with multiple cells containing select boxes. The code I have can create/delete rows relative to the entry which you click "+/-" from. I would like it so that if I press "+" then my program will look at the employee chosen in the above entry and have it as the selected value in the current (or new) entry.
I am having a hard time grabbing the value of the field, as well as making it the selected value.
Here is my code:
[JS]
function createRow(id, emp = null) {
var newrow = [
id,
'<select class="browser-default custom-select">' + employee_list + '</select>', // Want to add 'emp' here as selected element
'<select class="browser-default custom-select"></select>',
'<div class="input-group"><input type="number" min="0" step="0.5" class="form-control"><div class="input-group-append"><span class="input-group-text">hours</span></div>',
'<div class="input-group"><div class="input-group-prepend"><span class="input-group-text">$</span></div><input type="number" step="0.01" min="0" class="form-control"></div>',
'<textarea class="form-control" maxlength="200"></textarea>',
'<a class="addButton"><i class="fa fa-plus"></i></a> <a class="deleteButton"> <i class="fa fa-minus"></i></a>'
];
return '<tr><td>' + newrow.join('</td><td>') + '</td></tr>';
}
function renumberRows() {
$('table#budget tbody tr').each(function(index) {
$(this).children('td:first').text(index + 1);
});
}
$('#add').click(function() {
var lastvalue = 1 + parseInt($('table#budget tbody').children('tr:last').children('td:first').text());
$('table#budget tbody').append(createRow(lastvalue));
});
$('table#budget').on('click', '.addButton', function() {
$(this).closest('tr').after(createRow(0));
console.log($(this).closest('tr').children('td:nth-child(2)').val()); // tring to get previous entries selected employee
renumberRows();
}).on('click', '.deleteButton', function() {
$(this).closest('tr').remove();
renumberRows();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="pure-table pure-table-horizontal" id="budget" style="width: 100%" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>Row</th>
<th>Employee</th>
<th>Task</th>
<th>Budget</th>
<th>Expense</th>
<th>Comments</th>
<th><a id="add" style="float: right; color: #0000EE">Add Row <i class="fa fa-plus"></i></a></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<select class="browser-default custom-select" id="emp" size="1">
<option disabled selected>Choose Employee</option>
<?php for($i=0;$i<count($options_2);$i++){echo $options_2[$i];} ?>
</select>
</td>
<td>
<select class="browser-default custom-select" id="task" size="1">
<option disabled selected>Pick Employee</option>
</select>
</td>
<td>
<div class="input-group">
<input type="number" min="0" step="0.5" class="form-control">
<div class="input-group-append">
<span class="input-group-text">hours</span>
</div>
</td>
<td>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">$</span>
</div>
<input type="number" step="0.01" min="0" class="form-control">
</div>
</td>
<td><textarea class="form-control" maxlength="200"></textarea></td>
<td><a class="addButton"><i class="fa fa-plus"></i></a>
<a class="deleteButton"> <i class="fa fa-minus"></i></a>
</td>
</tr>
<!-- This is our clonable table line -->
</tbody>
</table><br>
example
The expected result would be to have the employee of the previous (or above) entry as the selected value in the new row upon clicking +. Or in the photo, the blacked out name would be showing where Choose Employee is.
EDIT: the global variable employee_list is an array containing all of the employees in html options format.

It would be easier if createRow() converted the HTML to DOM elements. Then you can use jQuery methods to find the select and set its value.
Use $(this).closest('tr').find('select:first').val() to get the employee from the row where you clicked Add.
It would also be a good idea to add distinct classes to specific inputs and selects, rather than using selectors like select:first to find a particular select in the row.
function createRow(id, emp = null) {
var newrow = [
id,
'<select class="browser-default custom-select">' + employee_list + '</select>', // Want to add 'emp' here as selected element
'<select class="browser-default custom-select"></select>',
'<div class="input-group"><input type="number" min="0" step="0.5" class="form-control"><div class="input-group-append"><span class="input-group-text">hours</span></div>',
'<div class="input-group"><div class="input-group-prepend"><span class="input-group-text">$</span></div><input type="number" step="0.01" min="0" class="form-control"></div>',
'<textarea class="form-control" maxlength="200"></textarea>',
'<a class="addButton"><i class="fa fa-plus"></i></a> <a class="deleteButton"> <i class="fa fa-minus"></i></a>'
];
var elts = $('<tr><td>' + newrow.join('</td><td>') + '</td></tr>');
if (emp !== null) {
elts.find("select:first").val(emp);
}
return elts;
}
function renumberRows() {
$('table#budget tbody tr').each(function(index) {
$(this).children('td:first').text(index + 1);
});
}
$('#add').click(function() {
var lastvalue = 1 + parseInt($('table#budget tbody').children('tr:last').children('td:first').text());
$('table#budget tbody').append(createRow(lastvalue));
});
$('table#budget').on('click', '.addButton', function() {
var prevemp = $(this).closest('tr').find('select:first').val();
$(this).closest('tr').after(createRow(0, prevemp));
console.log($(this).closest('tr').children('td:nth-child(2)').val()); // tring to get previous entries selected employee
renumberRows();
}).on('click', '.deleteButton', function() {
$(this).closest('tr').remove();
renumberRows();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="pure-table pure-table-horizontal" id="budget" style="width: 100%" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>Row</th>
<th>Employee</th>
<th>Task</th>
<th>Budget</th>
<th>Expense</th>
<th>Comments</th>
<th><a id="add" style="float: right; color: #0000EE">Add Row <i class="fa fa-plus"></i></a></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<select class="browser-default custom-select" id="emp" size="1">
<option disabled selected>Choose Employee</option>
<?php for($i=0;$i<count($options_2);$i++){echo $options_2[$i];} ?>
</select>
</td>
<td>
<select class="browser-default custom-select" id="task" size="1">
<option disabled selected>Pick Employee</option>
</select>
</td>
<td>
<div class="input-group">
<input type="number" min="0" step="0.5" class="form-control">
<div class="input-group-append">
<span class="input-group-text">hours</span>
</div>
</td>
<td>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">$</span>
</div>
<input type="number" step="0.01" min="0" class="form-control">
</div>
</td>
<td><textarea class="form-control" maxlength="200"></textarea></td>
<td><a class="addButton"><i class="fa fa-plus"></i></a>
<a class="deleteButton"> <i class="fa fa-minus"></i></a>
</td>
</tr>
<!-- This is our clonable table line -->
</tbody>
</table><br>

Related

Dynamic row calculation with Jquery

I want to make sum of dynamic rows and addition.
<div class="row">
<div class="col-md-8">
<div class="table-responsive">
<table id="test-table" class="table table-bordered">
<thead>
<tr>
<th>Product</th>
<th>Price </th>
<th><input id='add-row' class='btn btn-primary' type='button' value='Add' /> </th>
</tr>
</thead>
<tbody id="test-body">
<tr id="row0" class="products">
<td>
<select name="product_id[]" id="" class="form-control">
<option value="">-- Select Product --</option>
#foreach ($product as $row )
<option value="{{ $row->id }}">{{ $row->product_name }}</option>
#endforeach
</select>
</td>
<td>
<input name="price[]" type="number" min="1" class="form-control input-md price" />
</td>
<td>
<input class="delete-row btn btn-primary" type="button" value="Delete" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col-md-4">
<div class="col-xs-6">
<p>Previous Due</p>
</div>
<div class="col-xs-6">
<input type="text" class="form-control" value="5000" readonly>
</div>
<div class="col-xs-6">
<p>Total Price</p>
</div>
<div class="col-xs-6">
<input type="text" class="form-control total_price" value="" readonly>
</div>
<div class="col-xs-6">
<p>Pay Now</p>
</div>
<div class="col-xs-6">
<input type="number" class="form-control">
</div>
<div class="col-xs-6">
<p>Total Due</p>
</div>
<div class="col-xs-6">
<input type="number" value="" class="form-control">
</div>
</div>
</div>
Script:
<script type="text/javascript">
var row=1;
$(document).on("click", "#add-row", function () {
var new_row = '<tr id="row' + row + '" class="products"><td> <select name="product_id[]' + row + '" id="" class="form-control"> <option value="">-- Select Product --</option> #foreach ($product as $row ) <option value="{{ $row->id }}">{{ $row->product_name }}</option>#endforeach </select></td><td><input name="price[]' + row + '" type="number" min="1" class="form-control price" /></td><td><input class="delete-row btn btn-primary" type="button" value="Delete" /></td></tr>';
$('#test-body').append(new_row);
row++;
return false;
});
$(document).on("click", ".delete-row", function () {
if(row>0) {
$(this).closest('tr').remove();
row--;
}
return false;
});
</script>
<script type="text/javascript">
function sumIt() {
var total = 0, val;
$('.price').each(function() {
val = $(this).val();
val = isNaN(val) || $.trim(val) === "" ? 0 : parseFloat(val);
total += val;
});
$('.total_price').val(Math.round(total));
}
$(function() {
$(document).on('input', '.price', sumIt);
sumIt()
});
</script>
If I delete product row, the total price field is not updating the calculation. Suppose I added 4 rows, and give price value, after that I remove two rows, but the total price holds the previous 4 rows sum, it didn't update when I remove any row.
Here I want to show the total sum of product in total price.
And the Total Due calculation will be total due = (previous due + total price)- pay now
thanks

How to access parent element and then get it's value and then append to other element when adding a row?

My goal is to get the previous value inside my input element labeled "SERIAL END" then automatically append it's value when adding a row to "SERIAL START" and not only append but will add +1 to it's value. The problem is I always get an undefine value, I don't know what is missing.
Here is the image
Here is the snippets
$(document).ready(function() {
$("#addrow").on("click", function() {
var startElement = $("#start");
var value = parseInt(startElement.val());
startElement.val(value);
var hidden = startElement.val();
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var newRow = $("<tr id='tablerow_" + hidden + "'>");
var cols = "";
cols +=
'<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name"id="model' +
hidden + '" class="form-control selectpicker show-menu-arrow " name="model[]" ><option selected disabled> Select your model name</option><?php $sql = mysqli_query($con,"call gettrial");
if(mysqli_num_rows($sql)>0){
while($row=mysqli_fetch_assoc($sql)){
echo "<option value=$row[id]>".$row['model_name']." </option>";
}
} ?></select></td>';
cols +=
'<td><input id="code' + hidden +
'" value="" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="number" class="form-control" id="serstart' + hidden +
'" name="serstart[]" readonly/></td>';
cols +=
'<td><input type="number" class="form-control" id="serend' + hidden +
'" name="serend[]" onkeyup="manage(this)" /></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
.find('.selectpicker')
.selectpicker({
liveSearch: true,
showSubtext: true
});
const hide = document.getElementById('start');
hide.value = (parseInt(hidden) + parseInt(1));
hidden++;
}
});
$('#remove').click(function() {
$("#myTable").each(function() {
if ($('tr', this).length > 2) {
$('tr:last', this).remove();
}
});
});
});
$('#addrow').click(function() {
var id = $(this).closest('tr').find('#tablerow_0').text();
var row = $(this).parent("tbody tr");
var rowin=$(this).parent('tr').find('input:number');
var rowprev=$(this).parent('tr').prev().find('input:last').val();
var rownext=$(this).parent('tr').next().find('input:first').val();
console.log($(this).parent('tr').prev().find('input:last'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-12">
<form class="className" name="form" id="form"
action="lot_registration_model_submit.php" data-toggle="validator"
enctype="multipart/form-data" method="POST">
<div class="form-group">
<label class="col-sm-3">Lot No.: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="lotno"
name="lotno" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Month of: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="date" id="monthof"
name="monthof" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial Start: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="number" id="serstart" name="serstart"
style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial End: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="number" id="serend"
name="serend" style="text-transform:uppercase" required>
</div>
</div>
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" disabled />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover"
id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow"
data-live-search="true" title="Select your model name"
onchange="selectmodel(this)" required>
<?php
$sql = mysqli_query($con,"SELECT model.id,model.model_name,model.code,model.status
FROM model left join grouped on model.id = grouped.modelandcode
WHERE cat_id='1' and model.status='1' and grouped.status is null
ORDER BY model_name ASC");
$con->next_result();
if(mysqli_num_rows($sql)>0)
{
while($row=mysqli_fetch_assoc($sql))
{
echo "<option value='".$row['id']."'>".$row['model_name']."</option>";
}
}
?>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" class="form-control"
</td>
</tr>
</tbody>
</table>
<input type="hidden" value="1" id="start" />
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check"> &nbsp Submit</span></button>
</form>
</div>
You can get length of tr inside tbody then using that length get reference of previous tr then use td:eq(3) this will search fourth td because index starts from 0 then use that value to get value and add it in newly created tr input .
Also , you don't need to use same php code to create select-box just clone first select-box and then use same to pass inside td which are newly created .
Then , to intialize selectpicker which are added dynamically use $("table.order-list tr:last").find(".selectpicker").. this line will get last tr which is added and then inside that tr it will selectpicker .
Demo Code :
$(document).ready(function() {
$('.selectpicker').selectpicker({
liveSearch: true,
showSubtext: true
});
$("#addrow").on("click", function() {
var cloned = $("tbody select:first").clone() //cloned first tr select
var value = $("tbody tr").length - 1 //get tr length - 1 (because tr start from 0 index)
var new_start = parseInt($("tbody tr:eq(" + value + ") td:eq(3) input").val()) + 1 //get previous input box value
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var newRow = $("<tr id='tablerow_'" + (value + 1) + "'>");
var cols = "";
cols += '<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name" class="form-control selectpicker show-menu-arrow " name="model[]" >' + $(cloned).html() + '</select></td>';
cols += '<td><input value="' + $("#lotno").val() + '" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="number" class="form-control" name="serstart[]" value="' + new_start + '" readonly/></td>';
cols +=
'<td><input type="number" class="form-control"name="serend[]" value="' + $("#serend").val() + '"/></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
//intialize selectpicker which added last
$("table.order-list tr:last").find('.selectpicker').selectpicker({
liveSearch: true,
showSubtext: true
});
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/css/bootstrap-select.min.css" integrity="sha512-ARJR74swou2y0Q2V9k0GbzQ/5vJ2RBSoCWokg4zkfM29Fb3vZEQyv0iWBMW/yvKgyHSR/7D64pFMmU8nYmbRkg==" crossorigin="anonymous"
/>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js" integrity="sha512-yDlE7vpGDP7o2eftkCiPZ+yuUyEcaBwoJoIhdXv71KZWugFqEphIS3PU60lEkFaz8RxaVsMpSvQxMBaKVwA5xg==" crossorigin="anonymous"></script>
<div class="col-lg-12">
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover" id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" value="11" class="form-control"> </td>
</tr>
</tbody>
</table>
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check"> &nbsp Submit</span></button>
</form>
</div>

How to make a dynamic change and access a parent element on a value using JQuery?

I have a form where it is related to my previous question here. What I want to do is to get the previous value inside my input element labeled "SERIAL END" then automatically appends it's value when adding a row to "SERIAL START", and not only append but will add +1 to it's value (this is solved), but I want to add a function when the value is already added, it will get the value of the edited parent element and can be changeable but still adds the children element's value by +1.
Here is my whole code
$(document).ready(function() {
$("#addrow").on("click", function() {
var startElement = $("#start");
var value = parseInt(startElement.val());
startElement.val(value);
var hidden = startElement.val();
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var lasttr = $('#tbl tr:last').attr('id');
var lastinsertedrow = lasttr.replace('tablerow_', '');
var end = $('#serend' + lastinsertedrow).val();
end = (parseInt(end) + parseInt(1));
var newRow = $("<tr id='tablerow_" + hidden + "'>");
var cols = "";
cols +=
'<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name"id="model' +
hidden + '" class="form-control selectpicker show-menu-arrow " name="model[]" required><option selected disabled> Select your model name</option><?php $sql = mysqli_query($con,"call gettrial");
if (mysqli_num_rows($sql) > 0) {
while ($row = mysqli_fetch_assoc($sql)) {
echo "<option value=$row[id]>".$row['model_name'].
" </option>";
}
} ? > < /select></td > ';
cols +=
'<td><input id="code' + hidden +
'" value="" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="text" class="form-control" id="serstart' + hidden +
'" name="serstart[]" value="' + end + '" readonly/></td>';
cols +=
'<td><input type="text" class="form-control" id="serend' + hidden +
'" name="serend[]" onchange="myChangeFunction(this)" required /></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
.find('.selectpicker')
.selectpicker({
liveSearch: true,
showSubtext: true
});
$("#serend" + hidden).on("change", function(e) {
var x = $("#serend").val()
if ($(this).val() > (x * 100) / 100) {
alert("You exceed in " + x + " pls do enter below or exact " + x)
}
})
const hide = document.getElementById('start');
hide.value = (parseInt(hidden) + parseInt(1));
hidden++;
}
});
$('#remove').click(function() {
$("#myTable").each(function() {
if ($('tr', this).length > 2) {
$('tr:last', this).remove();
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<?php
include ('../include/header_pis.php');
?>
<html>
<title>Lot_Registration</title>
<body>
<div id="wrapper">
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header"> Lot Registration
<a href="rbg_table.php">
<button class="btn btn-success pull-right">
<span class="fa fa-reply"> Back </span>
</button>
</a>
</h1>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-primary">
<div class="panel-heading">
Model Form
</div>
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
<form class="className" name="form" id="form" action="lot_registration_model_submit.php" data-toggle="validator" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label class="col-sm-3">Lot No.: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="lotno" name="lotno" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Month of: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="date" id="monthof" name="monthof" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial Start: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="serstart" name="serstart" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial End: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="serend" name="serend" style="text-transform:uppercase" required>
</div>
</div>
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" disabled />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover" id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<?php
$sql = mysqli_query($con,"SELECT model.id,model.model_name,model.code,model.status
FROM model
left join grouped on model.id = grouped.modelandcode
WHERE cat_id='1' and model.status='1' and grouped.status is null
ORDER BY model_name ASC");
$con->next_result();
if(mysqli_num_rows($sql)>0){
while($row=mysqli_fetch_assoc($sql)){
echo "<option value='".$row['id']."'>".$row['model_name']."</option>";
}
} ?>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="" class="form-control" readonly="" />
</td>
<td>
<input type="text" name="serstart[]" id="serstart0" class="form-control" readonly />
</td>
<td>
<input type="text" name="serend[]" id="serend0" class="form-control" onchange="myChangeFunction(this)" required />
</td>
</tr>
</tbody>
</table>
<input type="hidden" value="1" id="start" />
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check"> &nbsp Submit</span></button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<script>
As i said in comment you just need to get index of tr where input has changed and then using that access next tr input and add value there.
Demo Code :
$("[id*=serend]").on("change", function(e) {
var x = $("#serend").val()
if ($(this).val() > (x * 100) / 100) {
alert("You exceed in " + x + " pls do enter below or exact " + x)
} else {
//get index of tr
var row = $(this).closest('tr').index() + 1;
var end = $(this).val(); //get value of input change
end = (parseInt(end) + parseInt(1));
$("tbody tr:eq(" + row + ") td:eq(2) input").val(end) //add inside next input
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table width="100%" class="table order-list table-striped table-bordered table-hover" id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" value="11" class="form-control"> </td>
</tr>
<tr id="tablerow_1">
<td>
<select name="model[]" id="model1" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code1" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart1" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend1" value="" class="form-control"> </td>
</tr>
<tr id="tablerow_2">
<td>
<select name="model[]" id="model2" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code2" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart2" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend2" value="" class="form-control"> </td>
</tr>
</tbody>
</table>

Add two values of different textField to fill another textField on multiple lines

Whenever I input the value of quantity and unit cost for each line, I want to automatically display the multiplied result into the total cost field.
I wrote the jquery script below trying to figure out how to go about it but couldn't get it working
$('.unit, .quantity').on('change', function() {
// var quantity = $('#expenseslist-quantity').val();
// var unit = $('#expenseslist-unit_cost').val();
var total = 0;
$('.quantity, .unit').each(function(){
total = quantity * unit ;
});
$('#expenseslist-total_cost').val(total);
});
Kindly help.
Try to learn how to implement dynamic element
$('.unit, .quantity').on('change', function(event) {
var total1 = 0;
var total2 = 0;
var quantity1 = $('#expenseslist-quantity1').val();
var unit1 = $('#expenseslist-unit_cost1').val();
total1 = quantity1 * unit1 ;
$('#expenseslist-total_cost1').val(total1);
var quantity2 = $('#expenseslist-quantity2').val();
var unit2 = $('#expenseslist-unit_cost2').val();
total2 = quantity2 * unit2 ;
$('#expenseslist-total_cost2').val(total2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tbody>
<tr class="primary">
<td width="170">
<div class="form-group field-expenseslist-item_id">
<select id="expenseslist-item_id" class="form-control" name="ExpensesList[item_id][]" required="">
<option value="">Select an Item</option>
<option value="1">Vehicle General Repairs And Maintenance</option>
<option value="2">Transportation Cost</option>
</select>
<div class="help-block"></div>
</div>
</td>
<td width="450"><div class="form-group field-expenseslist-request_explanation">
<textarea id="expenseslist-request_explanation" class="form-control" name="ExpensesList[request_explanation][]" rows="2" required=""></textarea>
<div class="help-block"></div>
</div>
</td>
<td width="80"><div class="form-group field-expenseslist-quantity">
<input type="number" id="expenseslist-quantity1" class="form-control quantity" name="ExpensesList[quantity][]" value="0" required="">
<div class="help-block"></div>
</div>
</td>
<td width="130"><div class="form-group field-expenseslist-unit_cost">
<input type="number" id="expenseslist-unit_cost1" class="form-control unit" name="ExpensesList[unit_cost][]" value="0" required="">
<div class="help-block"></div>
</div>
</td>
<td width="150"><div class="form-group field-expenseslist-total_cost">
<input type="text" id="expenseslist-total_cost1" class="form-control total" name="ExpensesList[total_cost][]" value="0" readonly="readonly" required="">
<div class="help-block"></div>
</div>
</td>
<!-- <td>
<button>Add</button>
</td> -->
</tr>
<tr class="primary">
<td width="170">
<div class="form-group field-expenseslist-item_id">
<select id="expenseslist-item_id" class="form-control" name="ExpensesList[item_id][]" required="">
<option value="">Select an Item</option>
<option value="1">Vehicle General Repairs And Maintenance</option>
<option value="2">Transportation Cost</option>
</select>
<div class="help-block"></div>
</div>
</td>
<td width="450"><div class="form-group field-expenseslist-request_explanation">
<textarea id="expenseslist-request_explanation" class="form-control" name="ExpensesList[request_explanation][]" rows="2" required=""></textarea>
<div class="help-block"></div>
</div>
</td>
<td width="80"><div class="form-group field-expenseslist-quantity">
<input type="number" id="expenseslist-quantity2" class="form-control quantity" name="ExpensesList[quantity][]" value="0" required="">
<div class="help-block"></div>
</div>
</td>
<td width="130"><div class="form-group field-expenseslist-unit_cost">
<input type="number" id="expenseslist-unit_cost2" class="form-control unit" name="ExpensesList[unit_cost][]" value="0" required="">
<div class="help-block"></div>
</div>
</td>
<td width="150"><div class="form-group field-expenseslist-total_cost">
<input type="text" id="expenseslist-total_cost2" class="form-control total" name="ExpensesList[total_cost][]" value="0" readonly="readonly" required="">
<div class="help-block"></div>
</div>
</td>
<!-- <td>
<button>Add</button>
</td> -->
<td><div class="btn btn-sm btn-danger rmv">Delete</div></td></tr></tbody>
UPDATED ANSWER:
As per your recent information, I made required changes to the code.
PS: For this, you have to make some changes on your HTML too and have to insert data- attributes on them.
For Unit input: data-type="unit" data-field="field_{1}"
For Quantity input: data-type="qty" data-field="field_{1}"
For the output input area: data-field-count="field_{1}"
After that, try out this code:
$('.unit, .quantity').on('keyup', function() {
let fieldType = $(this).data('type'),
fieldCount = $(this).data('field'),
intOne = $(this).val(),
intTwo = 1
if (fieldType == 'qty') {
intTwo = $('input[data-type=qty]').val()
} else {
intTwo = $('input[data-type=unit]').val()
}
let total = intOne * intTwo
$('input[data-field-count='+ fieldCount +']').val(total);
});
OLD ANSWER:
Since your query is pretty vague, this is what I understood from it:
$('.unit, .quantity').on('keyup', function() {
let qty = $('#expenseslist-quantity').val(),
unit = $('#expenseslist-unit_cost').val()
let total = unit * qty
$('#expenseslist-total_cost').val(total);
});
I don't know why you are using the each loop. Are there more than one unit and quantity fields?

multi ng -repeat and remove rows in angular js

I'm new to AngularJs and I'm stuck in multi ng-repeat.
HTML CODE
<table class="table table-bordered tdPaddingNull verTop">
<thead>
<tr>
<th width="200px">Product Details </th>
<th width="250px">Current Availability</th>
<th width="200px">Batch </th>
<th>Quantity</th>
<th>Rate INR </th>
<th>Amt. INR</th>
<th>Converted Amount</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(i,product) in listproducts track by $index">
<td style="padding: 7px;">
<input auto-complete ui-items="prductdetail" ng-model="formData.product_name[i]" class="form-control form-white" my-id="{{i}}"/>
<input id="product_id{{i}}" placeholder="productid" type="hidden" value="" ng-model="formData.product_id[i]" my-id="{{i}}"/>
<a ng-click="addProductBatch()" title="Add Another Batch Quantity" style="float:right;"><i class="fa fa-plus" aria-hidden="true"></i> ADD BATCH </a>
</td>
<td class="line-item-column item-currentavail transferorder-lineitem">
<div class="row text-muted font-sm">
<div class="col-md-6">
Source Stock
</div>
<div class="separationline col-md-6">
Destination Stock
</div>
</div>
<div class="row font-xs">
<div class="col-md-6">
0.00 Units
</div>
<div class="separationline col-md-6">
0.00 Units
</div>
</div>
</td>
<td style="padding: 7px;">
<div style="display:inline-block;width:100%;" ng-repeat="addBatch in listAddbatches">
<select class="form-control form-white selectNor" ng-model="formData.batch_id[i]" ng-change="changedBatchValue(formData.batch_id)" style="margin-bottom: 5px;width: 88%;float: left;">
<option value="">Select Batch</option>
<option value="{{blist.batch_id}}" ng-repeat="blist in batchList">{{blist.batch_number}}</option>
</select>
<a class="inputTabel1" ng-click="removeBatch($index)" title="Remove Batch" style="float:left;margin-left: 4px;"> <i class="fa fa-times-circle-o" aria-hidden="true" ></i>
</a>
</div>
</td>
<td style="padding: 7px;">
<input class="form-control form-white" type="text" value="" ng-model="formData.product_count[i]" ng-repeat="addBatch in listAddbatches" style="margin-bottom: 5px;"/>
</td>
<td style="padding: 7px;">
<input class="form-control form-white " placeholder="Selling Price" type="text" value="0.00" ng-model="formData.sel_inr_rate[i]">
</td>
<td>
<input class="form-control form-white form-Tabel" placeholder="Amount in INR" type="text" value="0.00" ng-model="formData.sel_inr_amount[i]" readonly />
</td>
<td class="Amount ">
<input class="form-control form-white form-Tabel" placeholder="" type="text" value="0.00" ng-model="formData.exc_total_amount[i]" readonly />
<button class="inputTabel" ng-click="removeProduct($index)"> <i class="fa fa-times-circle-o" aria-hidden="true"></i>
</button>
</td>
</tr>
</tbody>
</table>
ANGULAR CODE
/****************ADD ANOTHER BATCH QUANTITY**************/
$scope.addAnotherProduct = function(listproducts,$event) {
newItemNo = $scope.listproducts.length+1;
$scope.listproducts.push({'batch_id[newItemNo]':'','product_count[newItemNo]':''});
};
$scope.removeProduct = function(index) {
/*var lastItem = $scope.listproducts.length-1;
$scope.listproducts.splice(lastItem);
$scope.listAddbatches = '';*/
$scope.listproducts.splice(index,1);
};
$scope.removeBatch = function(index) {
/*var lastItem = $scope.listAddbatches.length-1;
$scope.listAddbatches.splice(lastItem);
$scope.listAddbatches = '';*/
$scope.listAddbatches.splice(index,1);
};
$scope.addProductBatch = function() {
var newItemNo = $scope.listAddbatches.length+1;
$scope.listAddbatches.push({'id':'batch'+newItemNo});
};
Here when I click ADD ANOTHER PRODUCT it should create an entire row in the table without the columns of Batch and Quantity, but now it's appearing as it in before row created.
Then when I click ADD BATCH it should create under the table column Batch and Quantity of the corresponding row, but now it's adding in all the rows and when I remove added batch, it should remove the corresponding batch, but now it's removing the last added batch.
The same happens when I remove added product (Entire Row), it should remove the corresponding row of the product but now it's removing lastly added Product row.
How can I fix all the aforementioned issues?
Please help me
There are multiple issues with your approach:
1) You are using a global array listAddbatches but you want to add the batches by product, so why shouldn't you use product.listAddbatches array?
2) When using track by $index you will not able to delete correct element from array or object since compiler directive is not re-compiling the element when its data attribute changes.
3) Using array length to generate id like var newItemNo = $scope.listAddbatches.length + 1; is not a good idea since the array length could change (when removing items) in a way that you will have the same ids for different elements.
4) This line is very strange {'batch_id[newItemNo]':'','product_count[newItemNo]':''}, since you are calculating newItemNo, but this is a simple string 'batch_id[newItemNo]'. Why do you need this?
5) Do not recommend to use $index to remove items, since it could point to some other element in case of filtering.
Your code could like this (simplified version), hope this helps:
angular.module('plunker', [])
.controller('MainCtrl', function($scope) {
$scope.listproducts = [];
$scope.addAnotherProduct = function(listproducts) {
listproducts.push( {
listAddbatches: []
});
};
$scope.removeProduct = function(product) {
var index = $scope.listproducts.indexOf(product);
if (index >= 0)
$scope.listproducts.splice(index, 1);
};
$scope.removeBatch = function(product, batch) {
var index = product.listAddbatches.indexOf(batch);
if (index >= 0)
product.listAddbatches.splice(index, 1);
};
$scope.addProductBatch = function(product) {
product.listAddbatches.push({ });
};
});
<script src="https://code.angularjs.org/1.6.4/angular.js" ></script>
<html ng-app="plunker">
<body ng-controller="MainCtrl">
<table class="table table-bordered tdPaddingNull verTop">
<thead>
<tr>
<th width="200px">Product Details </th>
<th width="250px">Current Availability</th>
<th width="200px">Batch </th>
<th>Quantity</th>
<th>Rate INR </th>
<th>Amt. INR</th>
<th>Converted Amount</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(i, product) in listproducts">
<td style="padding: 7px;">
<input auto-complete ui-items="prductdetail" ng-model="formData.product_name[i]" class="form-control form-white" my-id="{{i}}"/>
<input id="product_id{{i}}" placeholder="productid" type="hidden" value="" ng-model="formData.product_id[i]" my-id="{{i}}"/>
<a ng-click="addProductBatch(product)" title="Add Another Batch Quantity" style="float:right;"><i class="fa fa-plus" aria-hidden="true"></i> ADD BATCH </a>
</td>
<td class="line-item-column item-currentavail transferorder-lineitem">
<div class="row text-muted font-sm">
<div class="col-md-6">
Source Stock
</div>
<div class="separationline col-md-6">
Destination Stock
</div>
</div>
<div class="row font-xs">
<div class="col-md-6">
0.00 Units
</div>
<div class="separationline col-md-6">
0.00 Units
</div>
</div>
</td>
<td style="padding: 7px;">
<div style="display:inline-block;width:100%;" ng-repeat="addBatch in product.listAddbatches">
<select class="form-control form-white selectNor" ng-model="formData.batch_id[i]" ng-change="changedBatchValue(formData.batch_id)" style="margin-bottom: 5px;width: 88%;float: left;">
<option value="">Select Batch</option>
<option value="{{blist.batch_id}}" ng-repeat="blist in batchList">{{blist.batch_number}}</option>
</select>
<a class="inputTabel1" ng-click="removeBatch(product, addBatch)" title="Remove Batch" style="float:left;margin-left: 4px;"> <i class="fa fa-times-circle-o" aria-hidden="true" ></i>
</a>
</div>
</td>
<td style="padding: 7px;">
<input class="form-control form-white" type="text" value="" ng-model="formData.product_count[i]" ng-repeat="addBatch in product.listAddbatches" style="margin-bottom: 5px;"/>
</td>
<td style="padding: 7px;">
<input class="form-control form-white " placeholder="Selling Price" type="text" value="0.00" ng-model="formData.sel_inr_rate[i]">
</td>
<td>
<input class="form-control form-white form-Tabel" placeholder="Amount in INR" type="text" value="0.00" ng-model="formData.sel_inr_amount[i]" readonly />
</td>
<td class="Amount ">
<input class="form-control form-white form-Tabel" placeholder="" type="text" value="0.00" ng-model="formData.exc_total_amount[i]" readonly />
<button class="inputTabel" ng-click="removeProduct(product)"> <i class="fa fa-times-circle-o" aria-hidden="true"></i>
</button>
</td>
</tr>
</tbody>
</table>
<button ng-click="addAnotherProduct(listproducts)">Add Another Product</button>
</body>
</html>

Categories

Resources