How to make dynamic table column in javascript using select option - javascript

How to if the teacher select Items (4) using JavaScript,
as you can see, the table row adjust, it depends on what Items that the user selected,
please help me guys
here's the example:
if the user select Items (3)
here is my html
<table class="tableattrib" id="myTables">
<tr>
<td colspan="1" class="tdhead1">Class</td>
<td colspan="20" class="tdcell">
<select>
<option>Grading Categories</option>
</select>
<select onchange="myFunction()">
<option>Items</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select>
<option>Section</option>
</select>
</td>
</tr>
<tr>
<td class="tdnb" colspan="21"><input id="myInput" type="text" placeholder="Search Student" class="search"></td>
</tr>
<tr>
<td colspan="1" class="tdhead">Student Name</td>
<td class="tdcell1"><input type="text" name="" id="datepicker" placeholder="mm/dd/yyyy" title="Quiz Date"/></td>
<td class="tdcell1"><input type="text" name="" id="datepicker1" placeholder="mm/dd/yyyy" title="Quiz Date"/></td>
<td class="tdcell1"><input type="text" name="" id="datepicker2" placeholder="mm/dd/yyyy" title="Quiz Date"/></td>
<td class="tdcell2">Average</td>
</tr>
<tbody id="myTable">
<tr id="myRow">
<td colspan="1" class="tdcell">Marvin Makalintal</td>
<td class="tdcell1"><input type="text" name=""/></td>
<td class="tdcell1"><input type="text" name=""/></td>
<td class="tdcell1"><input type="text" name=""/></td>
<td class="tdcell1"><input type="text" name=""/></td>
</tr>
<tr>
<td class="tdbtn" colspan="21"><button type="button" class="save">&plus; Save</button>
<button type="button" class="save">&check; Finalize</button></td>
</tr>
</tbody>
</table>
</body>
<script>
function myFunction() {
var row = document.getElementById("myRow");
var x = row.insertCell(1);
x.innerHTML = "New cell";
}
</script>

First, we pass this.value into myFunction.
- <select onchange="myFunction()">
+ <select onchange="myFunction(this.value)">
Next, we add id="headerRow" to the header row.
- <tr>
+ <tr id="headerRow">
<td colspan="1" class="tdhead">Student Name</td>
Then, we implement configureRow(row, numItems, innerHTMLFunc) to insert and delete cells.
Finally, we call configureRow in myFunction.
function configureRow(row, numItems, innerHTMLFunc) {
var numCells = numItems + 2;
while (row.childElementCount < numCells) {
var x = row.insertCell(row.childElementCount - 1);
x.innerHTML = innerHTMLFunc(row.childElementCount - 2);
}
while (row.childElementCount > numCells) {
row.deleteCell(row.childElementCount - 2);
}
}
function myFunction(numItems) {
numItems = Number(numItems);
var row = document.getElementById("headerRow");
configureRow(row, numItems, (itemNum) => `<td class="tdcell1"><input type="text" name="" id="datepicker${itemNum - 1 || ''}" placeholder="mm/dd/yyyy" title="Quiz Date" /></td>`);
var row = document.getElementById("myRow");
configureRow(row, numItems, (itemNum) => '<td class="tdcell1"><input type="text" name=""></td>');
}
<table class="tableattrib" id="myTables">
<tr>
<td colspan="1" class="tdhead1">Class</td>
<td colspan="20" class="tdcell">
<select>
<option>Grading Categories</option>
</select>
<select onchange="myFunction(this.value)">
<option>Items</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select>
<option>Section</option>
</select>
</td>
</tr>
<tr>
<td class="tdnb" colspan="21"><input id="myInput" type="text" placeholder="Search Student" class="search"></td>
</tr>
<tr id="headerRow">
<td colspan="1" class="tdhead">Student Name</td>
<td class="tdcell1"><input type="text" name="" id="datepicker" placeholder="mm/dd/yyyy" title="Quiz Date" /></td>
<td class="tdcell1"><input type="text" name="" id="datepicker1" placeholder="mm/dd/yyyy" title="Quiz Date" /></td>
<td class="tdcell1"><input type="text" name="" id="datepicker2" placeholder="mm/dd/yyyy" title="Quiz Date" /></td>
<td class="tdcell2">Average</td>
</tr>
<tbody id="myTable">
<tr id="myRow">
<td colspan="1" class="tdcell">Marvin Makalintal</td>
<td class="tdcell1"><input type="text" name="" /></td>
<td class="tdcell1"><input type="text" name="" /></td>
<td class="tdcell1"><input type="text" name="" /></td>
<td class="tdcell1"><input type="text" name="" /></td>
</tr>
<tr>
<td class="tdbtn" colspan="21"><button type="button" class="save">&plus; Save</button>
<button type="button" class="save">&check; Finalize</button></td>
</tr>
</tbody>
</table>

<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
function myFunction() {
alert(selectionnumber);
var intselectionnumber = 0;
intselectionnumber =document.getElementById("selectionnumber").value;
alert(intselectionnumber);
var table = document.getElementById("mytab1");
for (var i = 0, row; row = table.rows[i] ; i++) {
//iterate through rows
//rows would be accessed using the "row" variable assigned in the for loop
for (var j = 0, col; col = row.cells[j]; j++) {
if (j == 1) {
for ( k = 1; k <= intselectionnumber; k++)
{
var x = row.insertCell(j);
x.innerHTML = "<input type='text' name='' id='datepicker2' placeholder='mm/dd/yyyy' title='Quiz Date'/>";
}
}
}
}
}
</script>
<h1>The onclick Event</h1>
<table class="tableattrib" id="myTables">
<tr>
<td colspan="1" class="tdhead1">Class</td>
<td colspan="20" class="tdcell">
<select>
<option>Grading Categories</option>
</select>
<select id='selectionnumber' onchange="myFunction();">
<option value="0">Items</option>
<option value="1" selected='selected'>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select>
<option>Section</option>
</select>
</td>
</tr>
</table>
<table id='mytab1'>
<tr>
<td class="tdnb" colspan="21"><input id="myInput" type="text" placeholder="Search Student" class="search"></td>
</tr>
<tr>
<td colspan="1" class="tdhead">Student Name</td>
<td class="tdcell2">Average</td>
</tr>
<tr id="myRow">
<td colspan="1" class="tdcell">Marvin Makalintal</td>
<td class="tdcell1"><input type="text" name="" /></td>
</tr>
<tr>
<td class="tdbtn" colspan="21">
<button type="button" class="save">&plus; Save</button>
<button type="button" class="save">&check; Finalize</button>
</td>
</tr>
</table>
</body>
</html>

Related

HTML table format with javascript style-change

In my HTML table I would like to hide a question and show this if a specific option is chosen in the dropdown. This works fine with the code below, but the table isn't formatted right (two <td> in the space of one)?
Demo (pick "Other type" at "Type")
How to fix this?
function setForm(value) {
if (value == '99') {
document.getElementById('form1').style = 'display:block;';
} else {
document.getElementById('form1').style = 'display:none;';
}
}
<form action="index.php" method="post">
<table cellspacing="0" cellpadding="0">
<tr>
<td>First question:</td>
<td><input type="text" name="firstone" /></td>
</tr>
<tr>
<td>Type: </td>
<td>
<select id="type" name="type" onchange="setForm(this.value)">
<option value="1">1</option>
<option value="2">2</option>
<option value="99">Other type</option>
</select>
</td>
</tr>
<tr id="form1" style="display:none;">
<td>Specify type:</td>
<td><input type="text" name="othertype" /></td>
</tr>
<tr>
<td>Description:</td>
<td><input type="text" name="description" minlength="10" maxlength="1000" /></td>
</tr>
</table>
<input type="submit" name="submit" value="Verstuur" />
</form>
Dont use block to display tr table element, just set style display to empty:
.style.display = '';
function setForm(value) {
if (value == '99') {
document.getElementById('form1').style.display = '';
} else {
document.getElementById('form1').style.display = 'none';
}
}
<form action="index.php" method="post">
<table cellspacing="0" cellpadding="0">
<tr>
<td>First question:</td>
<td><input type="text" name="firstone" /></td>
</tr>
<tr>
<td>Type: </td>
<td>
<select id="type" name="type" onchange="setForm(this.value)">
<option value="1">1</option>
<option value="2">2</option>
<option value="99">Other type</option>
</select>
</td>
</tr>
<tr id="form1" style="display:none;">
<td>Specify type:</td>
<td><input type="text" name="othertype" /></td>
</tr>
<tr>
<td>Description:</td>
<td><input type="text" name="description" minlength="10" maxlength="1000" /></td>
</tr>
</table>
<input type="submit" name="submit" value="Verstuur" />
</form>
The problem is, display:block for a tr element. Try this:
function setForm(value) {
if (value == '99') {
document.getElementById('form1').style = 'display:table-row;';
} else {
document.getElementById('form1').style = 'display:none;';
}
}
<form action="index.php" method="post">
<table cellspacing="0" cellpadding="0">
<tr>
<td>First question:</td>
<td><input type="text" name="firstone" /></td>
</tr>
<tr>
<td>Type: </td>
<td>
<select id="type" name="type" onchange="setForm(this.value)">
<option value="1">1</option>
<option value="2">2</option>
<option value="99">Other type</option>
</select>
</td>
</tr>
<tr id="form1" style="display:none;">
<td>Specify type:</td>
<td><input type="text" name="othertype" /></td>
</tr>
<tr>
<td>Description:</td>
<td><input type="text" name="description" minlength="10" maxlength="1000" /></td>
</tr>
</table>
<input type="submit" name="submit" value="Verstuur" />
</form>

An invalid form control with name='AdjustmentBuyerPrice' is not focusable

Below is the HTML and the JavaScript being used to display the dropdown only if one of the options from the preceding dropdown is selected. When I select the one that is linked the following dropdown it works while when I select the second option not linked to the following dropdown and click submit, it throws the error "An invalid form control with name='AdjustmentBuyerPrice' is not focusable". Please point out the mistake that I did in my code.
`{include file="header.tpl" page_name='Amazon Order Adjustment' extra_javascript='<script language="JavaScript" src="includes/update_shipping_info.js"></script>'}
{literal}
<style type="text/css">
#loading-icon {
position: absolute;
top: 75px;
right: 250px; width:
32px; height: 32px;
display: none;
background: url('/images/lightbox/loading.gif');
}
</style>
{/literal}
{if isset($tpl_error_msg) }
<div id="message">{$tpl_error_msg}</div>
{/if}
{include file='view_order_snippet.tpl'}
<form name="amazon_order_adjustment" id="amazon_order_adjustment" method="post" action="amazon_order_adjustment.php?id={$id}&{$search_params}">
<div class="row">
<fieldset>
<legend>Order Line Items</legend>
<table id="table2" style="position: relative; float: left;">
<tr valign="top">
<th width="10%"></th>
<th width="10%">SKU</th>
<th width="30%">Item</th>
<th width="5%">Qty</th>
<th width="10%">Status</th>
<th width="15%">Ship Mode</th>
<th width="20%">Tracking#</th>
</tr>
{if !($update_shipping_info_flag)}
<tr>
<td colspan="7" align="center">No Items to display</td>
</tr>
{else}
{section name=lineitems loop=$tpl_order_list}
<tr id=row1 valign="top">
<td><input type="radio" name="check[]" value="{$tpl_order_list[lineitems].id}">
<input type="hidden" name="vendor_id_array[]" value="{$tpl_order_list[lineitems].vendor_fk}">
</td>
<td>{$tpl_order_list[lineitems].sku}
<td>{$tpl_order_list[lineitems].item_description}</td>
<td>{$tpl_order_list[lineitems].quantity}</td>
<td>{$tpl_order_list[lineitems].item_status}</td>
<td>{$tpl_order_list[lineitems].shipping_mode}</td>
{if $tpl_order_list[lineitems].shipping_tracking_no == ""}
<td>N/A</td>
{else}
<td>{$tpl_order_list[lineitems].shipping_tracking_no}</td>
{/if}
</tr>
{/section}
{/if}
<tr>
<td align="right" colspan="3">Action Type</td>
<td align="left" colspan="4">
<select id="action_type" name="action_type" required>
<option value="">Select Action</option>
{html_options options=$tpl_action_type}
</select>
</td>
</tr>
<tr>
<td align="right" colspan="3">Enter Refund Amount</td>
<td align="left" colspan="4"><input type="number" step="1" min="" id="refund_amount" name="refund_amount" value="" required /></td>
</tr>
<tr>
<td align="right" colspan="3">Adjustment Reason</td>
<td align="left" colspan="4">
<select id="AdjustmentReason" name="AdjustmentReason" required>
<option value="" selected="selected">Select Adjustment Reason</option>
{html_options options=$tpl_adjustment_reason}
</select>
</td>
</tr>
<tr>
<td align="right" colspan="3">Adjustment Type</td>
<td align="left" colspan="4">
<select id="adjustment_type" name="adjustment_type" required>
<option value="" selected="selected">Select Adjustment Type</option>
{html_options options=$tpl_adjustment_type}
</select>
</td>
</tr>
<tr id="adjustment_buyer_price">
<td align="right" colspan="3">Adjustment Buyer Price Type</td>
<td align="left" colspan="4">
<select id="AdjustmentBuyerPrice" name="AdjustmentBuyerPrice" required>
<option value="">Select Adjustment Buyer Price Type</option>
{html_options options=$tpl_adjustment_buyer_price}
</select>
</td>
</tr>
</table>
</fieldset>
</div>
<div class="row">
<input type="hidden" id="tpl_grand_total_box" name="tpl_grand_total_box" value="{$tpl_grand_total}">
<input type="hidden" id="tpl_tax_box" name="tpl_tax_box" value="{$tpl_tax}">
<input type="submit" id="save_button" name="submit_action" value="refund" class="button">
<input type="submit" id="cancel_button" name="cancel_action" value="Cancel" class="button">
</div>
</div>
</form>
{literal}
<script type="text/javascript">
$(document).ready(function() {
$('#adjustment_buyer_price').hide();
$("#adjustment_type").change(function () {
var cur_option_val = $(this).val();
if (cur_option_val == "ItemPriceAdjustments") {
$('#adjustment_buyer_price').show();
$('#AdjustmentBuyerPrice').attr("required", "required") //add required
} else {
$('#adjustment_buyer_price').hide();
$('#AdjustmentBuyerPrice').removeAttr("required") //remove required.
}
});
});
</script>
{/literal}
{include file="footer.tpl"}
This is happening because you have AdjustmentBuyerPrice as required so when you have not selected value ItemPriceAdjustments its hidden and when you click on submit button that error shows .Instead you can remove required attribute when that select box is hidden else add required attribute .
Demo Code :
$(document).ready(function() {
$('#adjustment_buyer_price').hide();
$("#adjustment_type").change(function() {
var cur_option_val = $(this).val();
if (cur_option_val == "ItemPriceAdjustments") {
$('#adjustment_buyer_price').show();
$('#AdjustmentBuyerPrice').attr("required", "required") //add required
} else {
$('#adjustment_buyer_price').hide();
$('#AdjustmentBuyerPrice').removeAttr("required") //remove
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="amazon_order_adjustment" id="amazon_order_adjustment" method="post" action="amazon_order_adjustment.php?id={$id}&{$search_params}">
<div class="row">
<fieldset>
<legend>Order Line Items</legend>
<table id="table2" style="position: relative; float: left;">
<tr valign="top">
<th width="10%"></th>
<th width="10%">SKU</th>
<th width="30%">Item</th>
<th width="5%">Qty</th>
<th width="10%">Status</th>
<th width="15%">Ship Mode</th>
<th width="20%">Tracking#</th>
</tr>
<tr>
<td colspan="7" align="center">No Items to display</td>
</tr>
<tr id=row1 valign="top">
<td><input type="radio" name="check[]" value="1">
<input type="hidden" name="vendor_id_array[]" value="2">
</td>
<td>A
<td>B</td>
<td>5</td>
<td>ok</td>
<td>htm</td>
<td>N/A</td>
</tr>
<tr>
<td align="right" colspan="3">Action Type</td>
<td align="left" colspan="4">
<select id="action_type" name="action_type" required>
<option value="">Select Action</option>
<option value="">A</option>
</select>
</td>
</tr>
<tr>
<td align="right" colspan="3">Enter Refund Amount</td>
<td align="left" colspan="4"><input type="number" step="1" min="" id="refund_amount" name="refund_amount" value="" required /></td>
</tr>
<tr>
<td align="right" colspan="3">Adjustment Reason</td>
<td align="left" colspan="4">
<select id="AdjustmentReason" name="AdjustmentReason" required>
<option value="" selected="selected">Select Adjustment Reason</option>
<option value="">A</option>
</select>
</td>
</tr>
<tr>
<td align="right" colspan="3">Adjustment Type</td>
<td align="left" colspan="4">
<select id="adjustment_type" name="adjustment_type" required>
<option value="" selected="selected">Select Adjustment Type</option>
<option value="ItemPriceAdjustments">ItemPriceAdjustments</option>
<option value="ItemPriceAdjustments1">5</option>
</select>
</td>
</tr>
<tr id="adjustment_buyer_price">
<td align="right" colspan="3">Adjustment Buyer Price Type</td>
<td align="left" colspan="4">
<!--remove required from here-->
<select id="AdjustmentBuyerPrice" name="AdjustmentBuyerPrice">
<option value="">Select Adjustment Buyer Price Type</option>
<option value="">A</option>
</select>
</td>
</tr>
</table>
</fieldset>
</div>
<input type="submit" id="save_button" name="submit_action" value="refund" class="button">
</form>

Calculate load based on value return 0 or NaN

User will enter three values quantity, load, duration and then click on total button to show the multiplication in the watt hour textbox. But I always ended up getting a 0 or NaN.I tried with input type="number" but always getting the same result. Here is the code:
$(document).ready(function() {
var quantityval = parseInt($("#quantity").text(), 10);
var wattsval = $("#wattage option:selected").val();
var duration = parseInt($("#duration_use").text(), 10);
$("#total").click(function() {
var totalval = (quantityval * wattsval) * duration;
$("#watt-hour").val(totalval);
console.log($("#watt_hour").val(totalval));
});
<table class="table-bordered table table-md text-center table-responsive table-lg" id="table">
<thead class="bg-primary">
<tr>
<th colspan="2">Load Type</th>
<th>Quantity</th>
<th>Wattage (W)</th>
<th>Duration Use</th>
<th>Watt Hour</th>
<th>Total</th>
</tr>
</thead>
<tbody class="bg-success">
<tr>
<td colspan="2">
<select class="form-control" id="type">
<option>Fan</option>
<option>Iron</option>
<option>Blub</option>
<option>Motor</option>
<option>AC</option>
</select>
</td>
<td><input type="text" size="10px" class="form-control" id="quantity" /></td>
<td>
<!-- <input type="text" name="wattage" id="wattage" placeholder="Enter Consumption in Watts" class="form-control"> -->
<select class="form-control" id="wattage">
<option>25</option>
<option>30</option>
<option>45</option>
<option>80</option>
<option>100</option>
<option>120</option>
<option>1000</option>
<option>1500</option>
<option>2000</option>
<option>2500</option>
</select>
</td>
<td><input type="text" size="10px" class="form-control" id="duration_use" /></td>
<td><textarea size="10px" class="form-control" id="watt_hour" style="height: 38px;overflow: hidden;resize: none;"></textarea></td>
<td><button id="total" class="btn-success btn" style="padding: 5px">Total</button></td>
</tr>
</tbody>
</table>
Multiple issues here,
use val instead of text
directly take the value of select instead of its option
Put the fetch of values in the click event
use watt_hour instead of watt-hour while setting value.
Make it
var quantityval = +$("#quantity").val();
var wattsval = +$("#wattage").val();
var duration = +$("#duration_use").val();
Note
parseInt is fine, I am simply putting unary + for keeping it short.
Demo
$(document).ready(function() {
$("#total").click(function() {
var quantityval = +$("#quantity").val();
var wattsval = +$("#wattage").val();
var duration = +$("#duration_use").val();
console.log(quantityval, wattsval, duration);
var totalval = (quantityval * wattsval) * duration;
console.log(quantityval, wattsval, duration, totalval);
$("#watt_hour").val(totalval);
console.log($("#watt_hour").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table-bordered table table-md text-center table-responsive table-lg" id="table">
<thead class="bg-primary">
<tr>
<th colspan="2">Load Type</th>
<th>Quantity</th>
<th>Wattage (W)</th>
<th>Duration Use</th>
<th>Watt Hour</th>
<th>Total</th>
</tr>
</thead>
<tbody class="bg-success">
<tr>
<td colspan="2">
<select class="form-control" id="type">
<option>Fan</option>
<option>Iron</option>
<option>Blub</option>
<option>Motor</option>
<option>AC</option>
</select>
</td>
<td><input type="text" size="10px" class="form-control" id="quantity" /></td>
<td>
<!-- <input type="text" name="wattage" id="wattage" placeholder="Enter Consumption in Watts" class="form-control"> -->
<select class="form-control" id="wattage">
<option>25</option>
<option>30</option>
<option>45</option>
<option>80</option>
<option>100</option>
<option>120</option>
<option>1000</option>
<option>1500</option>
<option>2000</option>
<option>2500</option>
</select>
</td>
<td><input type="text" size="10px" class="form-control" id="duration_use" /></td>
<td><textarea size="10px" class="form-control" id="watt_hour" style="height: 38px;overflow: hidden;resize: none;"></textarea></td>
<td><button id="total" class="btn-success btn" style="padding: 5px">Total</button></td>
</tr>
</tbody>
</table>
Replace .text() with .val() and retrive all the values inside the click event handle
$(document).ready(function() {
$("#total").click(function() {
var quantityval = parseInt($("#quantity").val(), 10);
var wattsval = $("#wattage option:selected").val();
var duration = parseInt($("#duration_use").val(), 10);
var totalval = (quantityval * wattsval) * duration;
console.log(totalval)
$("#watt_hour").val(totalval);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table-bordered table table-md text-center table-responsive table-lg" id="table">
<thead class="bg-primary">
<tr>
<th colspan="2">Load Type</th>
<th>Quantity</th>
<th>Wattage (W)</th>
<th>Duration Use</th>
<th>Watt Hour</th>
<th>Total</th>
</tr>
</thead>
<tbody class="bg-success">
<tr>
<td colspan="2">
<select class="form-control" id="type">
<option>Fan</option>
<option>Iron</option>
<option>Blub</option>
<option>Motor</option>
<option>AC</option>
</select>
</td>
<td><input type="text" size="10px" class="form-control" id="quantity" /></td>
<td>
<!-- <input type="text" name="wattage" id="wattage" placeholder="Enter Consumption in Watts" class="form-control"> -->
<select class="form-control" id="wattage">
<option>25</option>
<option>30</option>
<option>45</option>
<option>80</option>
<option>100</option>
<option>120</option>
<option>1000</option>
<option>1500</option>
<option>2000</option>
<option>2500</option>
</select>
</td>
<td><input type="text" size="10px" class="form-control" id="duration_use" /></td>
<td><textarea size="10px" class="form-control" id="watt_hour" style="height: 38px;overflow: hidden;resize: none;"></textarea></td>
<td><button id="total" class="btn-success btn" style="padding: 5px">Total</button></td>
</tr>
</tbody>
</table>

Adding a row into my table which contain a select won't work

I want to add a row to my table to allow to the user to add data which will be inserted then into the data base.
I have imbricated tables (the coed given present just first row to simplify but it’s a long form given as a table).
My first problem is when I add the select to my getElementById it won’t work?
My second problem I don’t know if I can recuperate the fields added by the user and inserted them to my database?
I found the example that I have followed in ( Add table row in jQuery )
<html>
<head>
<script type="text/javascript">
function displayResult() {
document.getElementById("tabsalaire").insertRow(-1).innerHTML = '<td><input name="salaireparstatut4" id="salaireparstatut4" /></td>';
document.getElementById("tabtitulaire").insertRow(-1).innerHTML = '<td><input name="nbtitulaire4" id="nbtitulaire4" /></td>';
document.getElementById("tabfemale").insertRow(-1).innerHTML = '<td><input name="nbfemale4" id="nbfemale4" /></td>';
document.getElementById("tabsommeparstatut").insertRow(-1).innerHTML = '<td><input name="sommeparstatut4" id="sommeparstatut4" /></td>';
document.getElementById("selectstatus").insertRow(-1).innerHTML = '<td><select name="statutselect4" required> < option value = "" > choisir < /option> < option value = "Professeur" > Professeur < /option> < option value = "Assistant" > Assistant < /option> < /select> < input type = "hidden"
name = "EnseignementSuperieur"
value = "EnseignementSuperieur" / > < /td>';
}
</script>
</head>
<body>
<form method="post" action="processform.php">
<table border="1">
<tr>
<th>Add</th>
<th>Salaire annuel</th>
<th>nombre titulaire</th>
<th>Nombre femme</th>
<th>Somme</th>
<th>Statut</th>
<th>Type</th>
</tr>
<td>
<table>
<tr>
<td>
<button type="button" onClick="displayResult()">Insert new row</button>
</td>
</tr>
</table>
</td>
<td>
<table id="tabsalaire">
<tr>
<td>
<input name="salaireparstatut1" id="salaireparstatut1" />
</td>
</tr>
<tr>
<td>
<input name="salaireparstatut2" id="salaireparstatut2" />
</td>
</tr>
<tr>
<td>
<input name="salaireparstatut3" id="salaireparstatut3" />
</td>
</tr>
</table>
</td>
<td>
<table id="tabtitulaire">
<tr>
<td>
<input name="nbtitulaire1" id="nbtitulaire1" />
</td>
</tr>
<tr>
<td>
<input name="nbtitulaire2" id="nbtitulaire2" />
</td>
</tr>
<tr>
<td>
<input name="nbtitulaire3" id="nbtitulaire3" />
</td>
</tr>
</table>
</td>
<td>
<table id="tabfemale">
<tr>
<td>
<input name="nbfemale1" id="nbfemale1" />
</td>
</tr>
<tr>
<td>
<input name="nbfemale2" id="nbfemale2" />
</td>
</tr>
<tr>
<td>
<input name="nbfemale3" id="nbfemale3" />
</td>
</tr>
</table>
</td>
<td>
<table id="tabsommeparstatut">
<tr>
<td>
<input name="sommeparstatut1" id="sommeparstatut1" /> </td>
</tr>
<tr>
<td>
<input name="sommeparstatut2" id="sommeparstatut2" />
</td>
</tr>
<tr>
<td>
<input name="sommeparstatut3" id="sommeparstatut3" />
</td>
</tr>
</table>
</td>
<td>
<table id="selectstatus">
<tr>
<td>
<select name="statutselect1" required>
<option value="">choisir</option>
<option value="Professeur">Professeur</option>
<option value="Assistant">Assistant</option>
</select>
<input type="hidden" name="designationtypecadre1" value="EnseignementSuperieur" /> </td>
</tr>
<tr>
<td>
<select name="statutselect2">
<option value="">choisir</option>
<option value="Professeur">Professeur</option>
<option value="Assistant">Assistant</option>
</select>
<input type="hidden" name="designationtypecadre2" value="EnseignementSuperieur" /> </td>
</tr>
<tr>
<td>
<select name="statutselect3">
<option value="">choisir</option>
<option value="Professeur">Professeur</option>
<option value="ProfesseurConf">ProfesseurConf</option>
<option value="Assistant">Assistant</option>
</select>
<input type="hidden" name="designationtypecadre3" value="EnseignementSuperieur" /> </td>
</tr>
<tr></tr>
</table>
</td>
<th>
EnseignementSuperieur </th>
</tr>
<td> </td>
<td>
<input name="SubSommenbTitulaireTypeCadre" id="SubSommenbTitulaireProfChercheur" />
</td>
<td>
<input name="SubSommenbFemaleTypeCadre" id="SubSommenbFemaleProfChercheur" />
</td>
<td>
<input name="SubSommeNbProfTypeCadre" id="SubSommeNbProfChercheur" />
</td>
<td>
<input name="SubSommeSalaireAnnuelTypeCadre" id="SubSommeSalaireAnnuelProfChercheur" />
</td>
<th>Somme SUB</th>
<tr>
</tr>
<tr>
<td>
<input type="submit" name="Validate" value="Validate" />
</td>
</tr>
</table>
</body>
</html>

Calculate Total value for two input fields based on items selected from a select option tag in table

I want to get the value of the Amount pass to either Debit Amount or Credit Amount base on the Type selected if DR is select, then the value should be pass to Debit Amount and if CR is selected, then the value should be pass to Credit Amount. Total Amount should be passed in case of multiple Type options are selected
The HTML
<div>
<label style="margin-bottom:3px;">Debit Amount</label><span>
<input type="text" name="total_debit" id="totalDebit"/></span>
</div>
<div>
<label>Credit Amount</label><span>
<input type="text" name="total_credit" id="totalCredit" /></span>
</div>
<table class="table-bordered table-hover">
<thead>
<tr>
<th width="2%"><input id="check_all" type="checkbox"/></th>
<th width="5%">Type</th>
<th width="5%">Account Code</th>
<th width="15%">Account Name</th>
<th width="10%">Fund</th>
<th width="10%">Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="case" type="checkbox"/></td>
<td><select name="account_id[]" class=" mySelect" id="type_1">
<option value="000"></option>
<option value="1">DR</option>
<option value="2">CR</option>
</select>
</td>
<td>
<input type="text" name="accountCode[]" id="accountCode_1">
</td>
<td>
<input type="text" name="accountName[]" id="accountName_1"></td>
<td>
<select name="fund_id[]" >
<option></option>
</select>
</td>
<td>
<input type="text" name="amount[]" id="amount_1" class="totalLineAmount">
</td>
</tr>
<tr>
<td><input class="case" type="checkbox"/></td>
<td><select name="account_id[]" class=" mySelect" id="type_2">
<option value="000"></option>
<option value="1">DR</option>
<option value="2">CR</option>
</select>
</td>
<td>
<input type="text" name="accountCode[]" id="accountCode_2">
</td>
<td>
<input type="text" name="accountName[]" id="accountName_2"></td>
<td>
<select name="fund_id[]" >
<option></option>
</select>
</td>
<td>
<input type="text" name="amount[]" id="amount_2" class="totalLineAmount">
</td>
</tr>
<tr>
<td><input class="case" type="checkbox"/></td>
<td><select name="account_id[]" class=" mySelect" id="type_3">
<option value="000"></option>
<option value="1">DR</option>
<option value="2">CR</option>
</select>
</td>
<td>
<input type="text" name="accountCode[]" id="accountCode_3">
</td>
<td>
<input type="text" name="accountName[]" id="accountName_3"></td>
<td>
<select name="fund_id[]" >
<option></option>
</select>
</td>
<td>
<input type="text" name="amount[]" id="amount_3" class="totalLineAmount">
</td>
</tr>
<tr>
<td><input class="case" type="checkbox"/></td>
<td><select name="account_id[]" class=" mySelect" id="type_4">
<option value="000"></option>
<option value="1">DR</option>
<option value="2">CR</option>
</select>
</td>
<td>
<input type="text" name="accountCode[]" id="accountCode_4">
</td>
<td>
<input type="text" name="accountName[]" id="accountName_4"></td>
<td>
<select name="fund_id[]" >
<option></option>
</select>
</td>
<td>
<input type="text" name="amount[]" id="amount_4" class="totalLineAmount">
</td>
</tr>
</tbody>
</table>
Jquery Script
<script>
$(function(){
$(document).on("change",".mySelect",function(e){
e.preventDefault();
var _this=$(this);
var id =_this.val();
if ( id == 1) {
calculateTotalDebit();
}else if (id == 2) {
calculateTotalCredit();
}
function calculateTotalDebit(){
total = 0;
$('.totalLineAmount').each(function(){
if($(this).val() != '' )total += parseFloat( $(this).val() );
$('#totalDebit').val( total.toFixed(2) );
});
}
function calculateTotalCredit(){
total = 0;
$('.totalLineAmount').each(function(){
if($(this).val() != '' )total += parseFloat( $(this).val() );
});
$('#totalCredit').val( total.toFixed(2) );
}
});
});
</script>
$('.totalLineAmount') is selecting all of the amount inputs, so the calculateTotalDebit and calculateTotalCredit functions are adding them all regardless of the DR/CR type. You can check for the type inside the functions, for calculateTotalDebit for example:
function calculateTotalDebit(){
var total = 0;
$('.totalLineAmount').each(function(){
var thisNumber = $(this).attr('id').slice(-1);
// select the type of this amount
var type = $('#type_' + thisNumber);
// add only if the type is DR (val == 1)
if($(this).val() != '' && type.val() == 1)total += parseFloat( $(this).val() );
$('#totalDebit').val( total.toFixed(2) );
});
$(function() {
$(document).on("change", ".mySelect", function(e) {
e.preventDefault();
var _this = $(this);
var id = _this.val();
if (id == 1) {
calculateTotalDebit();
} else if (id == 2) {
calculateTotalCredit();
}
function calculateTotalDebit() {
total = 0;
$('.totalLineAmount').each(function() {
var thisNumber = $(this).attr('id').slice(-1);
// select the type of this amount
var type = $('#type_' + thisNumber);
// add only if the type is DR (val == 1)
if ($(this).val() != '' && type.val() == 1) total += parseFloat($(this).val());
$('#totalDebit').val(total.toFixed(2));
});
}
function calculateTotalCredit() {
total = 0;
$('.totalLineAmount').each(function() {
var thisNumber = $(this).attr('id').slice(-1);
// select the type of this amount
var type = $('#type_' + thisNumber);
// add only if the type is CR (val == 2)
if ($(this).val() != '' && type.val() == 2) total += parseFloat($(this).val());
});
$('#totalCredit').val(total.toFixed(2));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label style="margin-bottom:3px;">Debit Amount</label><span>
<input type="text" name="total_debit" id="totalDebit"/></span>
</div>
<div>
<label>Credit Amount</label><span>
<input type="text" name="total_credit" id="totalCredit" /></span>
</div>
<table class="table-bordered table-hover">
<thead>
<tr>
<th width="2%">
<input id="check_all" type="checkbox" />
</th>
<th width="5%">Type</th>
<th width="5%">Account Code</th>
<th width="15%">Account Name</th>
<th width="10%">Fund</th>
<th width="10%">Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input class="case" type="checkbox" />
</td>
<td>
<select name="account_id[]" class=" mySelect" id="type_1">
<option value="000"></option>
<option value="1">DR</option>
<option value="2">CR</option>
</select>
</td>
<td>
<input type="text" name="accountCode[]" id="accountCode_1">
</td>
<td>
<input type="text" name="accountName[]" id="accountName_1">
</td>
<td>
<select name="fund_id[]">
<option></option>
</select>
</td>
<td>
<input type="text" name="amount[]" id="amount_1" class="totalLineAmount">
</td>
</tr>
<tr>
<td>
<input class="case" type="checkbox" />
</td>
<td>
<select name="account_id[]" class=" mySelect" id="type_2">
<option value="000"></option>
<option value="1">DR</option>
<option value="2">CR</option>
</select>
</td>
<td>
<input type="text" name="accountCode[]" id="accountCode_2">
</td>
<td>
<input type="text" name="accountName[]" id="accountName_2">
</td>
<td>
<select name="fund_id[]">
<option></option>
</select>
</td>
<td>
<input type="text" name="amount[]" id="amount_2" class="totalLineAmount">
</td>
</tr>
<tr>
<td>
<input class="case" type="checkbox" />
</td>
<td>
<select name="account_id[]" class=" mySelect" id="type_3">
<option value="000"></option>
<option value="1">DR</option>
<option value="2">CR</option>
</select>
</td>
<td>
<input type="text" name="accountCode[]" id="accountCode_3">
</td>
<td>
<input type="text" name="accountName[]" id="accountName_3">
</td>
<td>
<select name="fund_id[]">
<option></option>
</select>
</td>
<td>
<input type="text" name="amount[]" id="amount_3" class="totalLineAmount">
</td>
</tr>
<tr>
<td>
<input class="case" type="checkbox" />
</td>
<td>
<select name="account_id[]" class=" mySelect" id="type_4">
<option value="000"></option>
<option value="1">DR</option>
<option value="2">CR</option>
</select>
</td>
<td>
<input type="text" name="accountCode[]" id="accountCode_4">
</td>
<td>
<input type="text" name="accountName[]" id="accountName_4">
</td>
<td>
<select name="fund_id[]">
<option></option>
</select>
</td>
<td>
<input type="text" name="amount[]" id="amount_4" class="totalLineAmount">
</td>
</tr>
</tbody>
</table>
I guess you have to update both "Debit Amount" and "Credit Amount" boxes, so you have to call both functions each time. It may be better to merge both functions into one calculateAmounts function. I'd also add event listeners to the .totalLineAmount boxes to update the totals automatically.
Try this code instead (demo):
$(function() {
function calculateTotals() {
var DRTotal = 0,
CRTotal = 0;
$('.totalLineAmount').each(function() {
var $this = $(this),
val = $this.val() || 0,
type = $this.closest('tr').find('.mySelect').val();
if (val && type === "1") {
DRTotal += parseFloat(val);
} else if (val && type === "2") {
CRTotal += parseFloat(val);
}
});
$('#totalDebit').val(DRTotal.toFixed(2));
$('#totalCredit').val(CRTotal.toFixed(2));
}
$(document).on("change", ".mySelect, .totalLineAmount", function(e) {
e.preventDefault();
calculateTotals();
});
});
In my opinion, you should add event listener on each input, calculate and put proper data into total amount in your callback function like
$('.myInputClass').on('change', function() {
// your code here..
updateAmountField(amount);
});
function updateAmountField(amount) {
$('.myTotalAmountInput').value(amount);
}

Categories