HTML table format with javascript style-change - javascript

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>

Related

How to make dynamic table column in javascript using select option

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>

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>

Autofill other fields automatically if one field is entered with jquery

Please check my fiddle.
Fiddle
When i enter any data in any rows in slab_range, i need to autofill all the other rows of 'Slab Range' with a value 'No Bid'. If i left blank, nothing has to be filled. Likewise if i enter any data in 'Part Number', all the other rows of 'Part Number' has to be filled with value '2'. The rows are coming from db, so i cant tell how many rows it will be, it should iterate all the rows.
<tr>
<td>
<input size="1" id="sl[0]" name="sl[0]" value="1" type="text">
</td>
<td>
<input size="9" data-validation="required" name="slab_range[]" id="slab_range[]" type="text">
</td>
<td>
<input size="9" name="item_partno[]" id="item_partno[]" type="text">
</td>
</tr>
There you go, now it's your task to refactoring the code because both methods are equals.
var ProcessTable = (function () {
var _slabs, _partsNumber;
var _init = function () {
_slabs = $('input[name^="slab_range"]');
_partsNumber = $('input[name^="item_partno"]');
_slabs.on('blur', _slabBlurHandler);
_partsNumber.on('blur', _partNumberBlurHandler);
};
var _slabBlurHandler = function (e) {
var value = $.trim($(this).val());
if (value !== '') {
_slabs.val('No bid');
} else {
_slabs.val('');
}
$(this).val(value); // Because the previous line override the original value
};
var _partNumberBlurHandler = function (e) {
var value = $.trim($(this).val());
if (value !== '') {
_partsNumber.val('2');
} else {
_partsNumber.val('');
}
$(this).val(value); // Because the previous line override the original value
};
return {
init: _init
}
})();
ProcessTable.init();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="cart1" name="cart" method="post" class="single" action="price_edit_save.php?supplier_name=Jupiter+Microwave+Components+Inc&tender_id=151501">
<div class="clone_row">
<table style="border-collapse: collapse;" id="table" border="1" cellpadding="2" cellspacing="2" width="100%">
<thead>
<tr bgcolor="#E6E6FA">
<th width="4%">SlNo</th>
<th width="4%">Slab Range</th>
<th width="6%">Part Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input size="1" name="id[0]" value="9978" readonly="readonly" type="hidden">
<input size="1" id="sl[0]" name="sl[0]" value="1" type="text">
<input size="1" id="item_id[0]" name="item_id[0]" readonly="readonly" type="hidden">
</td>
<td>
<input size="9" data-validation="required" name="slab_range[]" id="slab_range[]" type="text">
</td>
<td>
<input size="9" name="item_partno[]" id="item_partno[]" type="text">
</td>
</tr>
<tr>
<td>
<input size="1" name="id[1]" value="9979" readonly="readonly" type="hidden">
<input size="1" id="sl[1]" name="sl[1]" value="2" type="text">
<input size="1" id="item_id[1]" name="item_id[1]" readonly="readonly" type="hidden">
</td>
<td>
<input size="9" data-validation="required" name="slab_range[]" id="slab_range[]" type="text">
</td>
<td>
<input size="9" name="item_partno[]" id="item_partno[]" type="text">
</td>
</tr>
<tr>
<td>
<input size="1" name="id[1]" value="9979" readonly="readonly" type="hidden">
<input size="1" id="sl[1]" name="sl[1]" value="2" type="text">
<input size="1" id="item_id[1]" name="item_id[1]" readonly="readonly" type="hidden">
</td>
<td>
<input size="9" data-validation="required" name="slab_range[]" id="slab_range[]" type="text">
</td>
<td>
<input size="9" name="item_partno[]" id="item_partno[]" type="text">
</td>
</tr>
</tbody>
</table>
</div>
<div class="addMoreDIV">
</div>
<table>
<tr>
<td>
<input value="--Update Data--" type="submit">
</td>
</tr>
</table>
</form>
And please, be more kindly when you ask for "help".

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);
}

javascript won't execute properly; unsure why. validating form

My javascript won't properly load. I am not sure why. I am new to programming/scripting.. i appreciate the help.
The idea behind this is to validate a form without using alerts, however it does not seem to execute at all.
Here's my code:
validateForm()
{
var province = document.getElementByID("province");
var postalcode = document.getElementByID("postalcode");
if(province.value == "Select a province")
{
document.write('Select your province from the list');
province.focus();
return false;
}
else
{
return true;
}
if(postalcode.length<6)
{
document.write("You must enter a valid postal code .");
}
var widget1qty=document.getElementById("widget1qty").innerHTML;
var widget2qty=document.getElementById("widget2qty").innerHTML;
var widget3qty=document.getElementById("widget3qty").innerHTML;
if(widget1qty ==0)
{
document.write("You must select some widgets.");
}
if(widget2qty < 0 )
{
document.write("You must select some widgets.");
}
if(widget3qty < 0 )
{
document.write("You must select some widgets.");
}
}
HTML:
<h2>Order Form</h2>
<form name="myForm" method="post" action="processForm.html" onsubmit="validateForm()">
<table>
<tr>
<th colspan="2">Personal Information</th>
</tr>
<tr>
<td>First Name:</td>
<td><input type="text" name="firstName" id="firstName" size="30" required></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="lastName" id="lastName" size="30" required></td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" name="address" id="address" size="30" required></td>
</tr>
<tr>
<td>City:</td>
<td><input type="text" name="city" id="city" size="30" required></td>
</tr>
<tr>
<td>Province:</td>
<td><select name="province" id="province" size="1" required>
<option disabled>Select a province</option>
<option value="BC">British Columbia</option>
<option value="AB">Alberta</option>
<option value="SK">Saskatchewan</option>
<option value="MB">Manitoba</option>
<option value="ON">Ontario</option>
<option value="QC">Québec</option>
<option value="NB">New Brunswick</option>
<option value="NS">Nova Scotia</option>
<option value="PE">Prince Edward Island</option>
<option value="NF">Newfoundland</option>
<option value="YK">Yukon</option>
<option value="NWT">Northwest Territories</option>
<option value="NU">Nunavut</option>
</select>
</td>
</tr>
<tr>
<td>Postal Code:</td>
<td><input type="text" name="postalCode" id="postalCode" maxlength="6" minlength="6" required></td>
</tr>
<tr>
<th colspan="2">Order Information</th>
</tr>
<tr>
<td rowspan="3">Select your products:<br>
<span id="productError" class="errorMessage" hidden></span></td>
<td>Widget #1
<input type="text" name="widget1qty" id="widget1qty" size="1" value="0">Qty # <strong>$5.00/ea</strong></td>
</tr>
<tr>
<td>Widget #2
<input type="text" name="widget2qty" id="widget2qty" size="1" value="0">Qty # <strong>$15.00/ea</strong></td>
</tr>
<tr>
<td>Widget #3
<input type="text" name="widget3qty" id="widget3qty" size="1" value="0">Qty # <strong>$25.00/ea</strong></td>
</tr>
<tr>
<td rowspan="3">Shipping Type:</td>
<td>Standard ($5.00)<input type="radio" name="shippingType" id="shippingTypeStandard" value="Standard" checked></td>
</tr>
<tr>
<td>Express ($10.00)<input type="radio" name="shippingType" id="shippingTypeExpress" value="Express"></td>
</tr>
<tr>
<td>Overnight ($20.00)<input type="radio" name="shippingType" id="shippingTypeOvernight" value="Overnight"></td>
</tr>
<tr>
<th colspan="2">Submit Order</th>
</tr>
<tr>
<td><input type="submit" name="btnSubmit" id="btnSubmit" value="Submit Order" onSubmit="validateForm()"></td>
<td><input type="reset" name="btnReset" id="btnReset" value="Reset Form" ></td>
</tr>
</table>
</form>
</body>
`
Is that your full javascript? It is going to be pulling an unexpected end since you haven't finished your closures. If you are using Google Chrome to view the HTML, hit F12 to get the developer tools and view the console.
Also it is getElementById or getElementsByName
document.getElementById(string);
That call can only return one element since Ids are unique.
document.getElementsByName(string);
That call can return multiple elements as names are not unique. Meaning you are going to get an array even if there is one.
You don't need the excess 'else's. If you don't have logic in it, no need to include it.
You are getting the same widget value and handing it into widgetqty1, widgetqty2, and widgetqty3.
You never close the function definition. You need the last ending curly brace (}) to make sure it is a valid function.
You should end up with the following code:
<html>
<head>
<script>
function validateForm(ev){
var province, postalcode, widget1qty, widget2qty, widget3qty;
province = document.getElementById("province");
postalcode = document.getElementById("postalcode");
widget1qty = document.getElementById("widget1qty").innerHTML;
widget2qty = document.getElementById("widget2qty").innerHTML;
widget3qty = document.getElementById("widget3qty").innerHTML;
if(province.value == "Select a province")
{
document.write('Select your province from the list');
// You realize this overwrites your entire document?
province.focus();
return false;
}
if(postalcode.length<6)
{
document.write("You must enter a valid postal code .");
// You realize this overwrites your entire document?
postcalcode.focus();
return false;
}
if(widget1qty == 0 || widget2qty < 0 || widget3qty < 0)
{
document.write("You must select some widgets.");
// You realize this overwrites your entire document?
return false;
}
}
</script>
</head>
<body>
<h2>Order Form</h2>
<form onsubmit="return validateForm()"name="myForm" method="post" action="processForm.html">
<table>
<tr>
<th colspan="2">Personal Information</th>
</tr>
<tr>
<td>First Name:</td>
<td><input type="text" name="firstName" id="firstName" size="30" required></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="lastName" id="lastName" size="30" required></td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" name="address" id="address" size="30" required></td>
</tr>
<tr>
<td>City:</td>
<td><input type="text" name="city" id="city" size="30" required></td>
</tr>
<tr>
<td>Province:</td>
<td><select name="province" id="province" size="1" required>
<option disabled>Select a province</option>
<option value="BC">British Columbia</option>
<option value="AB">Alberta</option>
<option value="SK">Saskatchewan</option>
<option value="MB">Manitoba</option>
<option value="ON">Ontario</option>
<option value="QC">Québec</option>
<option value="NB">New Brunswick</option>
<option value="NS">Nova Scotia</option>
<option value="PE">Prince Edward Island</option>
<option value="NF">Newfoundland</option>
<option value="YK">Yukon</option>
<option value="NWT">Northwest Territories</option>
<option value="NU">Nunavut</option>
</select>
</td>
</tr>
<tr>
<td>Postal Code:</td>
<td><input type="text" name="postalCode" id="postalCode" maxlength="6" minlength="6" required></td>
</tr>
<tr>
<th colspan="2">Order Information</th>
</tr>
<tr>
<td rowspan="3">Select your products:<br>
<span id="productError" class="errorMessage" hidden></span></td>
<td>Widget #1
<input type="text" name="widget1qty" id="widget1qty" size="1" value="0">Qty # <strong>$5.00/ea</strong></td>
</tr>
<tr>
<td>Widget #2
<input type="text" name="widget2qty" id="widget2qty" size="1" value="0">Qty # <strong>$15.00/ea</strong></td>
</tr>
<tr>
<td>Widget #3
<input type="text" name="widget3qty" id="widget3qty" size="1" value="0">Qty # <strong>$25.00/ea</strong></td>
</tr>
<tr>
<td rowspan="3">Shipping Type:</td>
<td>Standard ($5.00)<input type="radio" name="shippingType" id="shippingTypeStandard" value="Standard" checked></td>
</tr>
<tr>
<td>Express ($10.00)<input type="radio" name="shippingType" id="shippingTypeExpress" value="Express"></td>
</tr>
<tr>
<td>Overnight ($20.00)<input type="radio" name="shippingType" id="shippingTypeOvernight" value="Overnight"></td>
</tr>
<tr>
<th colspan="2">Submit Order</th>
</tr>
<tr>
<td><input type="submit" name="btnSubmit" id="btnSubmit" value="Submit Order" ></td>
<td><input type="reset" name="btnReset" id="btnReset" value="Reset Form" ></td>
</tr>
</table>
</form>
</body>

Categories