AJAX - Post Table Rows and Individual Inputs - javascript

I have a project in Laravel that I am working on and one portion requires me to work with submitting a form through a modal, the problem is I'm not as familiar with AJAX as I'd like to be and I've run into an issue.
Here are the modal contents:
<table>
<tr>
<td>
{{ csrf_field() }}
<select name="payer_id" class="js-basic-single payer_id" style="width:100%;" id="payer_id">
<option></option>
#foreach($customers as $customer)
<option value="{{ $customer->id }}">{{ $customer->customer_name }}</option>
#endforeach
</select>
<div id="existing_biller_details" class="hidden" name="existing_biller_details" style="margin-top:10px;">
</div>
<select class="form-control deposit_type" name="deposit_type" id="deposit_type">
<option disabled selected>Please Select</option>
<option value="Check">Check</option>
<option value="Cash">Cash</option>
<option value="ECheck">ECheck</option>
</select>
<div name="check_number" id="check_number" class="hidden">
<input type="text" placeholder="Check Number" class="form-control" id="check_number" name="check_number">
</div>
<input type="text" class="form-control" placeholder="Payment Amount" name="payment_amount" id="payment_amount">
<input type="date" class="form-control" placeholder="Date of Deposit" name="date_deposit" id="date_deposit">
<textarea placeholder="Notes" style="width:100%;" class="form-control" id="notes" name="notes"></textarea>
</td><td style="width:50%;">
<table style="width:100%;" id="freight_bill_items">
<thead>
<td style="width:30%;font-weight:bold;text-align:center;">Bill No.</td><td style="width:30%; font-weight:bold; text-align:center;">Amount</td>
</thead>
<tbody>
<tr style="height:40px">
<td style="width:30%;text-align:center;"><input type="text" name="payment_details[shipment_id][]" required class="form-control name_list" id="shipment_id" placeholder="Bill No." required></td><td style="width:30%;text-align:center;"><input type="text" name="payment_details[amount][]" required class="form-control name_list" id="amount" placeholder="Amount" required>
</td><td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</tbody>
</table>
<div id="freight_bill_items_subtotal;" style="font-weight:bold; padding-top:10px; padding-bottom:10px; text-align:left; background-color: #f0f8ff;">
SUBTOTAL:
<input type="text" readonly name="freightBillSubtotal" id="freightBillSubtotal" class="form-control total_field" style="display:inline;" value="0.00">
</div>
</td>
</tr>
</table>
As you can see a little bit lower, there is a div called "freight_bill_items", with a table and in the only tbody row, the two text inputs and a button to add another table row with the same exact inputs.
Now here at the moment is my ajax script:
<script type="text/javascript">
$(document).on('click', '.createPayment', function() {
$('.modal-title').text('Record New Payment');
$('#payment').modal('show');
});
$('.modal-footer').on('click', '.add_payment', function() {
//START
var payment_details = [];
//END
$.ajax({
type:'POST',
url: '/payments/createNew',
data: {
payer_id: $('input[name=payer_id]').val(),
notes: $('input[name=notes]').val(),
payment_amount: $('input[name=payment_amount]').val(),
date_deposit: $('input[name=date_deposit]').val(),
check_number: $('input[name=check_number]').val(),
deposit_type: $('input[name=deposit_type]').val(),
payment_details:payment_details, //LOOKING FOR ASSISTANCE HERE//
_token: $('input[name=_token]').val(),
},
success: function(data) {
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((data.errors)) {
setTimeout(function () {
$('#payment').modal('show');
toastr.error('Validation error - Check your inputs!', 'Error Alert', {timeOut: 5000});
}, 500);
if (data.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(data.errors.title);
}
if (data.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(data.errors.content);
}
} else {
toastr.success('Successfully recorded Payment!', 'Success Alert', {timeOut: 5000});
}
},
});
});
</script>
Now what I'm stuck on is how do I pass these rows and their input contents into arrays to POST along with the other values?

I would suggest that you remove id from inputs that are duplicated. Assign a class instead.The shipment id can be assigned as an attribute.
<input class="payment_details" shipment_id="{shipment_id}" value="" required>
function get_array(element){
// Inputs having mutliple fields(grouped by class) will be returned as an array
arr = [];
element.map(function(){
arr[$(this).attr('shipment_id')] = $(this).val();
});
return arr;
}
var payments = get_array($('.payment_details'));
You now have an array whose key is shipment_id and value is input value for the respective element. Pass this array in your AJAX.

Related

Javascript/Jquery : How can I show value which match with selected value on dynamic table?

I have a dynamic table where button on click add new row. Each row has a select value for product name and a input value for product price. I want to show the product price depends on the selected value. For backed I used Laravel 7. Below I added my code:
Table:
<button id="productAdd" type="button"> Add Row</button>
<table id="product-table" class="table table-bordered text-center">
<tr>
<td>
<select name="product_id[]" class="form-control" id="product-name">
<option value="" selected disabled>Select Product</option>
#foreach($product as $row)
<option value="{{ $row->id }}">{{ $row->name }}</option>
#endforeach
</select>
</td>
<td>
#foreach($product as $row)
<input id="price_{{ $row->id }}" value="{{ $row->price }}" type="number" class="form-control price" style="display:none;">
#endforeach
</td>
<td><button class="remove">Delete</button></td>
</tr>
</tbody>
</table>
This is the script where button on click add a new row:
$(function() {
const $tb = $('#product-table tbody');
$(".delete").eq(0).hide()
$("#productAdd").on("click",function() {
const $row = $tb.find("tr").eq(0).clone();
$(".delete",$row).show(); // show the hidden delete on this row
$row.find("select").val(""); // reset the select
$row.find("[type=number]").val(); // reset the numbers
$tb.append($row);
});
$tb.on('click', '.remove', function() {
$(this).parents('tr').remove();
});
});
Here I show all the product price and all are hidden. I want to show the price value which match with the selected value. For this I used id = price_{{ $row->id }}
#foreach($product as $row)
<input id="price_{{ $row->id }}" value="{{ $row->price }}" type="number" class="form-control price" style="display:none;">
#endforeach
And this is my script where showed the product price:
$('#product-name').on('change',function(){
$(".price").hide();
var price = $(this).find('option:selected').val();
$("#price_" + price).show();});
But this works for the first row only. How can I merge this script, so that it works for every new row added inside the table?
$(function() {
const $tb = $('#product-table tbody');
$(".remove").eq(0).hide()
$("#productAdd").on("click",function() {
const $row = $tb.find("tr").eq(0).clone();
$(".remove",$row).show(); // show the hidden delete on this row
$row.find("select").val(""); // reset the select
$row.find("[type=number]").val(); // reset the numbers
$tb.append($row);
});
$tb.on('click', '.remove', function() {
$(this).parents('tr').remove();
});
});
$('#product-name').on('change',function(){
$(".price").hide();
var price = $(this).find('option:selected').val();
$("#price_" + price).show();});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="productAdd" type="button"> Add Row</button>
<table id="product-table" class="table table-bordered text-center">
<tr>
<td>
<select name="product_id[]" class="form-control" id="product-name">
<option value="" selected disabled>Select Product</option>
<option value="1">Pant</option>
<option value="2">Shirt</option>
<option value="3">T-shirt</option>
</select>
</td>
<td>
<input id="price_1" value="100" type="number" class="form-control price" style="display:none;">
<input id="price_2" value="200" type="number" class="form-control price" style="display:none;">
<input id="price_3" value="50" type="number" class="form-control price" style="display:none;">
</td>
<td><button class="remove">Delete</button></td>
</tr>
</table>
With proper delegation it will work
As I said in my other answer, do not use ID
Here is a working version. See I changed the ID to class
$(function() {
const $tb = $('#product-table tbody');
$(".remove").eq(0).hide()
$("#productAdd").on("click", function() {
const $row = $tb.find("tr").eq(0).clone();
$(".remove", $row).show(); // show the hidden delete on this row
$row.find("select").val(""); // reset the select
$row.find("[type=number]").val(); // reset the numbers
$tb.append($row);
});
$tb.on('click', '.remove', function() {
$(this).closest('tr').remove();
});
$tb.on('change', '.product-name', function() {
const $row = $(this).closest('tr');
$(".price", $row).hide();
const whichPrice = $(this).val();
if (whichPrice != "") $(".price", $row).eq(whichPrice-1).show()
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="productAdd" type="button"> Add Row</button>
<table id="product-table" class="table table-bordered text-center">
<tr>
<td>
<select name="product_id[]" class="form-control product-name">
<option value="" selected disabled>Select Product</option>
<option value="1">Pant</option>
<option value="2">Shirt</option>
<option value="3">T-shirt</option>
</select>
</td>
<td>
<input value="100" type="number" class="form-control price" style="display:none;">
<input value="200" type="number" class="form-control price" style="display:none;">
<input value="50" type="number" class="form-control price" style="display:none;">
</td>
<td><button class="remove">Delete</button></td>
</tr>
</table>

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>

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

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>

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?

I do have a form wherein if a user enters input it should check for negative or empty input box and throw an alert message

Here is my code below. I do have a form wherein consists of three dropdowns and input boxes.So I do want to check whether a field is blank or for negative numbers being entered?
//Dependant dropdown code
$("#item").change(function() {
var iname = $(this).val();
$.post("fetch_data.php",
{"iname": iname},
function (data) {
document.getElementById('new_select').innerHTML=data;
});
});
$('#submitBtn').click(function(){
var txt = $(".check").val();
if(parseInt(txt) < 0 || txt == -1){
alert("Enter positive values ..!!!!");
}else{
$('#sess').text($('#sesion').val());
$('#ite').text($('#item').val());
$('#new').text($('#new_select').val());
$('#qin').text($('#qtyin').val());
$('#qout').text($('#qtyout').val());
}
});
$('#submit').click(function(){
$.ajax({
type:"POST",
url:'profile.php',
data:{sesion:$("#sess").text(),iname:$("#ite").text(),price:$("#new").text(),category:$("#qin").text(),qty:$("#qout").text()},
success: function(data){
$("#confirm-submit").modal("hide");
$("#result").html("<div class='alert alert-warning'>Record Inserted Successfully</div>");
setTimeout(function(){
$("#result").fadeOut();
},5000);
window.location.reload();
}
});
});
});
<form method='post' name='ireg' class="form-inline" role="form" id="formfield" enctype="multipart/form-data" onsubmit="return validateForm();">
<table id="entry" class="table table-responsive">
<tr>
<td> <label for="sesion">Session</label></td>
<td><select id="sesion" name="sesion" class="form-control check">
<option>--Select--</option>
<option>Breakfast</option>
<option>Lunch</option>
<option>Dinner</option>
</select></td>
<td> <label for="item_name">Item Name</label></td>
<td><select name="iname" id="item" class="form-control check" style="width:180px;">
<option>Select Item</option>
<?php
include 'db.php';
$select = $conn->query("SELECT item_name from items");
while($row = mysqli_fetch_array($select, MYSQLI_ASSOC))
{
echo "<option>".$row['item_name']."</option>";
}
?>
</select>
</td>
<td>
<label for="new_select">Price</label>
</td>
<td>
<select id="new_select" name="new_select" class="form-control check">
<option>Select Price</option>
</select>
</td>
<td>
<label for="qtyin">Qty(Dine In)</label>
</td>
<td>
<input type="number" id="qtyin" min="0" name="qtyin" class="check" placeholder="QTY Dine In" style="width:80px;"/>
</td>
<td>
<label for="qtyout">Qty(Parcel)</label>
</td>
<td>
<input type="number" id="qtyout" name="qtyout" min="0" class="check" placeholder="QTY Dine Out" style="width:80px;"/>
</td>
<td>
<!-- <button type="submit" name="submit" class="btn btn-primary">Submit</button> -->
<input type="button" name="submit" value="Submit" id="submitBtn" data-toggle="modal"
data-target="#confirm-submit" class="btn btn-success" />
</td>
</tr>
</table>
</form>
I am trying to take input from user where validation is needed and once it is validated goes to modal popup to confirm then submit process..
If HTML5 validation is supported, you do not need jQuery for validation.
<input type=number min=0 required placeholder='Enter a positive number'>
If you want a custom validation message, the following should do:
<input type=number min=0 required placeholder="Enter a positive number"
oninvalid="this.setCustomValidity('Enter User Name Here')"
oninput="setCustomValidity('')">
The :invalid psuedo class can be used to apply custom CSS to it.
This link contains some examples. For browser support see caniuse.
EDIT:
For dropdowns, you may use the required attribute.
<select required>
<option value="">None</option>
<option value="Option1">Option1</option>
<option value="Option2">Option2</option>
<option value="Option3">Option3</option>
</select>
Note that the first option has to be blank. For details on applying required to <select> see this question.

Categories

Resources