Checking table data if has input - javascript

I'm trying to check my table data for empty field. I used $('td:has(input)') because all of my cell has <input type="text" class="form-control">. What I want to do if the user hit the Save button it will checked if all the textfield is empty otherwise it will prompt a message. But the user can fill one of the textfields but cannot be left blank. How can I achieve this?
Table:
<div class = "col-md-12">
<table class = "table" id = "customFields">
<thead>
<tr>
<th>Stock No.</th>
<th>Unit</th>
<th class = "description">Description</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
</tr>
</tbody>
</table>
<button type = "submit" class = "btn btn-primary" id = "addMore">+ Add</button>
<button type = "submit" class = "btn btn-danger" id = "removeRow">- Remove</button>
<button type = "submit" class = "btn btn-primary" id = "save">Save</button>
</div>
Script:
<script>
$(document).ready(function ()
{
$("#addMore").click(function ()
{
$("#customFields").append('<tr><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td></tr>');
});
$("#removeRow").click(function()
{
if ($('#customFields tbody tr').length== 1)
{
alert('Cannot be left blank');
}
else
{
$('#customFields tr:last').remove();
}
});
$("#save").click(function ())
{
if ($('td:has(input)').text(function ()
{
}));
});
});
</script>

You could loop through all elements with the form-control class and make sure their combined values length is greater than zero.
$("#save").click(function (){
var values = "";
$.each($(".form-control"), function(i, c){
values = values + $(c).val().trim(); // .trim() to remove white-space
});
if(values.length > 0)
{
//Success!
}
else
{
// Error!
}
});

Related

Dynamic change of color and text of an element

The script below creates a new line of text boxes and a button. However, when the button is clicked, the new field would like to have new button text and a new design.
$(function () {
var newRow = $(".addRows").clone();
$("#addButton").on("click", function () {
let row = newRow.clone().appendTo("#TextBoxesGroup tbody");
$("tr").find("#addButton").css( "border-color", "red" );
});
});
<table id="TextBoxesGroup">
<tr class="addRows">
<td>Start Date:</td>
<td>
<input type="text" name="StartDate[]" class="picker" value="" size="6">
</td>
<td>End Date:</td>
<td>
<input type="text" name="EndDate[]" class="picker" value="" size="6">
</td>
<td>
<input type="button" id="addButton" value="add row" />
</td>
</tr>
</table>
<script type = "text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
For example, the created new button should be with text delete and color red.
Thanks for the help or recommendation
I think using templates might make it easier and cleaner to modify the elements. Here is a quick guide for basic templating with vanillajs https://gomakethings.com/html-templates-with-vanilla-javascript/
This allows you to easily pass in IDs for your inputs.
I am not sure if you are just trying to toggle a second row or add multiple rows. If you simply want to toggle the second row and not add more than that then only use the second part of the js, and remove the first template. Likewise if you want to add multiple you can remove the second part (currently commented out) of the js and the second template.
(function (){
// Interpolate function from https://gomakethings.com/html-templates-with-vanilla-javascript/
//Lets us pass a unique id to the template
function interpolate (str, params) {
let names = Object.keys(params);
let vals = Object.values(params);
return new Function(...names, `return \`${str}\`;`)(...vals);
}
//Using document on click as we are adding new buttons to the DOM and want the event to trigger on them as well
$(document).on('click', '.add-button', function () {
let id = $('.addRows').length + 1; //Use this for our row ID
let newRow = interpolate(row_template.innerHTML, {id}); //Generate our row html from the template
$(this).closest('.addRows').after(newRow); //Add the html to the table
});
//Remove button
$(document).on('click', '.remove-button', function () {
$(this).closest('.addRows').remove();
});
})();
//Use the below INSTEAD of the above for just the single extra toggling row.
/*(function (){
//Add new row from simple template
$(document).on('click', '.add-button', function () {
$("#TextBoxesGroup tbody").append(row_template_single.innerHTML);
});
//Remove the row
$(document).on('click', '.remove-button', function () {
$(this).closest('.addRows').remove();
});
})();*/
/*Style for red remove button*/
.remove-button {
background-color: #f77;
color: white;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<table id="TextBoxesGroup">
<tbody>
<tr class="addRows">
<td>Start Date:</td>
<td>
<input type="text" name="StartDate_1" class="picker" value="" size="6">
</td>
<td>End Date:</td>
<td>
<input type="text" name="EndDate_2" class="picker" value="" size="6">
</td>
<td>
<input type="button" id="addButton_1" class="add-button" value="Add row" />
</td>
</tr>
</tbody>
</table>
<!-- Template allowing to add multiple new rows with unique input names via id passed -->
<template id="row_template">
<tr class="addRows">
<td>Start Date:</td>
<td>
<input type="text" name="StartDate_${id}" class="picker" value="" size="6">
</td>
<td>End Date:</td>
<td>
<input type="text" name="EndDate_${id}" class="picker" value="" size="6">
</td>
<td>
<input type="button" id="addButton_${id}" class="add-button" value="Add row" />
<input type="button" class="remove-button" value="Remove row" />
</td>
</tr>
</template>
<!-- Template for just 'toggling' a second row -->
<!-- <template id="row_template_single">
<tr class="addRows">
<td>Start Date:</td>
<td>
<input type="text" name="StartDate_2" class="picker" value="" size="6">
</td>
<td>End Date:</td>
<td>
<input type="text" name="EndDate_2" class="picker" value="" size="6">
</td>
<td>
<input type="button" class="remove-button" value="Remove row" />
</td>
</tr>
</template> -->
I noticed my previous answer did not properly handle adding items in-between other items, i.e. not at the end of the list.
The following will better handle adding and removing items, while keeping the ids in order. This instead renders the fields based on the data we keep and manage in JavaScript.
(function () {
$(document).ready(function () {
field_data.init()
})
let field_data = {
data: [],
init: function () {
this.cacheDom();
this.bindEvents();
this.data.push(this.getItem());
this.renderData();
},
cacheDom: function () {
this.$render_container = $('#render_container');
this.row_template_html = $('#row_template').html();
},
bindEvents: function () {
$(document).on('click', '.remove-button', this.removeItem);
$(document).on('click', '.add-button', this.addItem);
this.$render_container.on('change', 'input', this.inputChange);
},
//When an item gets added, add new empty item to the data and re-render.
addItem: function () {
let target = parseInt($(this).attr('data-target'));
field_data.data.splice(target+1, 0, field_data.getItem());
field_data.renderData();
},
//When an item gets removed, remove it from the data and re-render.
removeItem: function () {
let target = parseInt($(this).attr('data-target'));
if (field_data.data.length > 1) { //Prevent from removing last item.
field_data.data.splice(target, 1);
field_data.renderData();
}
},
//Get a new/empty item.
getItem: function () {
return {
start_date: '',
end_date: '',
}
},
//Update the data when a value of an input changes
inputChange: function () {
let $this = $(this);
let id = parseInt($this.attr('data-id'));
let target = $this.attr('data-target');
field_data.data[id][target] = $this.val();
},
//Render the data according to the template.
renderData: function () {
let html = '';
for (let i = 0; i < field_data.data.length; i++) {
//Generate our row html from the template
html += field_data.getRowTemplate(
{
id: i,
start_date: field_data.data[i].start_date,
end_date: field_data.data[i].end_date,
}
);
}
field_data.$render_container.html(html);
},
//Gets the html for a single row based on our template
getRowTemplate: function (params) {
let names = Object.keys(params);
let values = Object.values(params);
return new Function(...names, `return \`${field_data.row_template_html}\`;`)(...values);
},
}
})();
.remove-button {
background-color: #f77;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="TextBoxesGroup">
<tbody id="render_container">
</tbody>
</table>
<template id="row_template">
<tr class="addRows">
<td>Start Date:</td>
<td>
<input type="text" name="StartDate_${id}" data-id="${id}" data-target="start_date" class="picker" value="${start_date}" size="6">
</td>
<td>End Date:</td>
<td>
<input type="text" name="EndDate_${id}" data-id="${id}" data-target="end_date" class="picker" value="${end_date}" size="6">
</td>
<td>
<input type="button" class="add-button" data-target="${id}" id="addButton_${id}" value="Add row"/>
<input type="button" class="remove-button" data-target="${id}" value="Remove row"/>
</td>
</tr>
</template>

Few field of INPUT form not allowing to enter Data

I have a form, there is a button (+sign)on the form which appends a row to insert the value .In my form i am able to enter the value on the first row both fields( stationerytype and stationeryqty). But once I append a new row by clicking plus button I am not able to insert any value on staionerytype field of second row while I'm able to insert the value in the stationeryqty field of second row.
My code is:
<table class="table table-bordered" id="tb" >
<tr class="tr-header">
<th class= "col-md-1" align="centre">Sl.No.</th>
<th class= "col-md-6" align="centre">STATIONARY TYPE</th>
<th class= "col-md-4" align="centre">STATIONARY QUANTITY</th>
<th class= "col-md-1"><span class="glyphicon glyphicon-plus"></span></th>
</tr>
<tr>
<?php
for($i=1;$i<=1;$i++)
{
?>
<td><input type="text" style="text-decoration: none" name="slno" value= "<?php echo $i; ?>" ></td>
<td><input type="text" style="text-decoration: none" name="stationerytype" ></td>
<td><input type="number" name="stationeryqtyrecd" id="stationeryqtyrecd" min="0"></td>
<td><a href='javascript:void(0);' class='remove'><span class='glyphicon glyphicon-remove'></span></a></td>
</tr>
<?php }?>
</table>
<button type="submit" name="add" class="btn btn-info" align="middle" >ADD </button>
<script>
var max = 4;
var count = 1;
$(function(){
$('#addMore').on('click', function() {
if(count <= max ){
var data = $("#tb tr:eq(1)").clone(true).appendTo("#tb");
data.find("input").val('');
debugger;
data.find("input")[0].value=++count;
}else{
alert("Sorry!! Can't add more than five samples at a time !!");
}
});
$(document).on('click', '.remove', function() {
var trIndex = $(this).closest("tr").index();
if(trIndex>1) {
$(this).closest("tr").remove();
} else {
alert("Sorry!! Can't remove first row!");
var trIndex = $(this).closest("tr").index();
if(trIndex>1) {
$(this).closest("tr").remove();
count--;
// get all the rows in table except header.
$('#tb tr:not(.tr-header)').each(function(){
$(this).find('td:first-child input').val(this.rowIndex);
})
}
});
});
</script>
</div>

disable button in case of empty element in class

I want to disable submit button if there is any empty field in class element.
$(document).ready(function (){
fees = [];
$('#button').attr('disabled',true);
});
function submitButton() {
// var fees = $('.fee').val();
var total = $('#total').val();
$(".fee").each(function(index, value){
fees.push($(this).val().trim());
});
if(fees.includes('') && total = '') {
$('#button').attr('disabled',true);
} else {
$('#button').attr('disabled',false);
} // /else
}//fuction
JS fiddle link
Just check if there is content inside the inputs, if you activate the button by removing the disabled class
$('input').on('keyup', function(){
var enable = true
$('input').each(function(index, element){
if ($(element).val() == "" || $(element).val() == null){
enable = false;
}
});
if (enable){
$('button').removeAttr('disabled');
}else{
$('button').attr('disabled','disabled');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" /><br /><br />
<input type="text" /><br /><br />
<input type="text" />
<button disabled>Confirm</button>
Edit 1.0:
$(document).ready(function (){
fees = [];
$('#button').attr('disabled',true);
});
//submit button enable disable
function submitButton() {
var total = $('#total').val();
$(".fee").each(function(index, value){
fees.push($(this).val().trim());
});
}//fuction
function disableButton(){
var enable = true
$('input.useToCheck').each(function(index, element){
if ($(element).val() == "" || $(element).val() == null){
enable = false;
}
});
if (enable){
$('button').removeAttr('disabled');
}else{
$('button').attr('disabled','disabled');
}
}
$('input').on('keyup', function(){
disableButton();
});
$('#more').on('click', function(){
disableButton();
});
//autocomplete script
$(document).on('focus','.search',function(){
let type = $(this).data('type');
$(this).autocomplete({
source: [{
label: 1,
value: 1,
data: {
t_id: 1,
Fee: 9.99
}
}, {
label: 2,
value: 2,
data: {
t_id: 2,
Fee: 1
}
}],
autoFocus: true,
minLength: 1,
select: function( event, ui ) {
let id_num = $(this).attr('id').substring(5);
$(this).val(ui.item.value);
$('#fee_' + id_num).val(ui.item.data.Fee);
$('#total').val(ui.item.data.Fee);
//$(this).attr('data-type', ui.item.type);
return false;
},
});
});
var i=$('table#first tr').length;
$("#more").on('click',function(){
html = '<tr>';
html += '<td><input type="text" data-type="type" onKeyUp="submitButton();" id="test_'+i+'" class="search useToCheck" placeholder="Enter 1 or 2 only"> </td>';
html += '<td><input type="number" id="fee_'+i+'" class="fee" placeholder="Fee"></td>';
html += '</tr>';
$('table#first').append(html);
i++;
disableButton();
$('input').on('keyup', function(){
disableButton();
});
});
#button {
margin: 50px;
}
<link href="https://code.jquery.com/ui/1.11.4/themes/ui-darkness/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<!--hidden div-->
<div class="Popup">
<table id="first">
<thead>
<tr>
<th>Name</th>
<th>Fee</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" data-type="type" onKeyUp="submitButton();" id="test_1" class="search useToCheck" placeholder="Enter 1 or 2 only"></td>
<td><input type="number" id="fee_1" class="fee" placeholder="Fee"></td>
<td><a id="more"> More Row </a></td>
</tr>
</tbody>
</table>
<h3> Table 2 </h3>
<table id="tests">
<thead>
<tr>
<th>Student</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" data-type="type" onKeyUp="submitButton();" id="student" class="search useToCheck"></td>
<td><input type="number" id="total"></td>
</tr>
</tbody>
</table>
</div>
<button type="button" id="button"> submit </button>
Add keyup event to the input, Check if the elements .fee and '#total have value and then enable the button else disable.
$(document).ready(function() {
const btn = $('button');
btn.attr('disabled', true);
$('input').on('keyup', function() {
const fees = $('.fee').val();
const total = $('#total').val();
const isDisabled = (fees && total) ? false : true;
btn.attr('disabled', isDisabled);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="Popup">
<table id="first">
<thead>
<tr>
<th>Name</th>
<th>Fee</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" data-type="type" id="test_1" class="search" placeholder="Enter 1 or 2 only"></td>
<td><input type="number" id="fee_1" class="fee" placeholder="Fee"></td>
<td><a id="more"> More Row </a></td>
</tr>
</tbody>
</table>
<h3> Table 2 </h3>
<table id="tests">
<thead>
<tr>
<th>Student</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" data-type="type" id="student" class="search"></td>
<td><input type="number" id="total"></td>
</tr>
</tbody>
</table>
</div>
<button type="button" id="button"> submit </button>

How I can put the required input fields in my Js code

How I can put the required fields in my Js code
I set required = true in xml view but it does blocker all the form
how to add required for the js code jQuery
this my code jQuery :
// table course
jQuery(document).ready(function() {
var id = 0;
var cr = 0;
jQuery("#addcourserow").click(function() {
id++;
var row = jQuery('.courserow tr').clone(true);
var c = 1;
row.find("input").each(function(){
if (c === 1) {
$(this).attr('name','course_name_'+id);
}
else if (c === 2) {
$(this).attr('name','course_duration_'+id);
}
else if (c === 3) {
$(this).attr('name','course_date_'+id);
}
c++;
});
row.appendTo('#CourseTable');
return false;
});
$('.remove').on("click", function() {
$(this).parents("tr").remove();
});
});
and this my XML
<!-- Course -->
<table id="CourseTable">
<thead>
<th>name</th>
<th>duration</th>
<th>date</th>
</thead>
<tr id="tr_course">
<td><input type="text" name="course_name_1" id="course_name"/></td>
<td><input type="text" name="course_duration_1" id="course_duration"/></td>
<td><input type="date" name="course_date_1" id="course_date" /></td>
<td><button class="remove">Remove</button></td>
</tr>
</table>
<input type="button" id="addcourserow" value="add row" />
<table class="courserow" style="display:none">
<tr>
<td><input type="text" id="course_name" /></td>
<td><input type="text" id="course_duration"/></td>
<td><input type="date" id="course_date"/></td>
<td><button class="remove">Remove</button></td>
</tr>
</table>
</div>
I added here in codepen
Please consider the following code.
$(function() {
var id = 0;
var cr = 0;
var names = [
"course_name",
"course_duration",
"course_date"
];
$("#addcourserow").click(function() {
var row = $('#course-row-template tr').clone(true);
id++;
var c = 0;
row.find("input").each(function() {
var inpId = $(this).attr("id") + "_" + id;
$(this).attr({
id: inpId,
name: names[c++] + "_" + id
}).prop("required", true);
console.log($(this));
});
row.appendTo('#CourseTable');
return false;
});
$('.remove').on("click", function() {
$(this).parents("tr").remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<table id="CourseTable">
<thead>
<th>name</th>
<th>duration</th>
<th>date</th>
</thead>
<tr id="tr_course">
<td><input type="text" id="course_name_0" /></td>
<td><input type="text" id="course_duration_0" /></td>
<td><input type="date" id="course_date_0" /></td>
<td><button class="remove">Remove</button></td>
</tr>
</table>
<input type="button" id="addcourserow" value="Add New Row" />
<table id="course-row-template" style="display:none">
<tr>
<td><input type="text" id="course_name" /></td>
<td><input type="text" id="course_duration" /></td>
<td><input type="date" id="course_date" /></td>
<td><button class="remove">Remove</button></td>
</tr>
</table>
This will ensure that each <input> has a unique ID and name. It also adds the required property to each of them.
Hope that helps.
i find answer
jQuery(document).ready(function() {
var id = 0;
jQuery("#addcourserow").click(function() {
id++;
var row = jQuery('.courserow tr').clone(true);
var c = 1;
row.find("input").each(function(){
if (c === 1) {
$(this).attr('name','course_name_'+id).prop("required", true);
}
else if (c === 2) {
$(this).attr('name','course_duration_'+id).prop("required", true);
}
else if (c === 3) {
$(this).attr('name','course_date_'+id).prop("required", true);
}
c++;
});
row.appendTo('#CourseTable');
return false;
});
$('.remove').on("click", function() {
$(this).parents("tr").remove();
});
});
and i add required in my Xml
<table id="CourseTable">
<thead>
<th>name</th>
<th>duration</th>
<th>date</th>
</thead>
<tr id="tr_course">
<td><input type="text" name="course_name_1" id="course_name" required="required"/></td>
<td><input type="text" name="course_duration_1" id="course_duration" required="required"/></td>
<td><input type="date" name="course_date_1" id="course_date" required="required"/></td>
<td><button class="remove">Remove</button></td>
</tr>
</table>

Javascript Forms Calculator with No answers

I am very new to really writing javascript (borrowing and editing, not so new). So with a little help from google and code guru and adobe cookbook, I have come up with this simple form to be embedded into an iPad publication (this is just my test, not the final product). I have gotten it this far with no errors if the debug console and it seems to pass W3C compliance, but it also doesn't do anything! It doesn't generate the answers??? I am hoping someone can help me out or steer me in the right direction. the code for the page is below: Thanks in advance...
<body>
<form id="form1" name="form1" method="post" action="">
<table width="500" border="1">
<tr>
<th scope="col">Item</th>
<th scope="col">Cost 1</th>
<th scope="col">Cost 2</th>
</tr>
<tr>
<th scope="row">Manikin</th>
<td><input type="text" name="ManikinCost1" id="ManikinCost1" tabindex="1" /></td>
<td><input type="text" name="ManikinCost2" id="ManikinCost2" tabindex="2" /></td>
</tr>
<tr>
<th scope="row">Instructor</th>
<td><input type="text" name="InstructorCost1" id="InstructorCost1" tabindex="3" /></td>
<td><input type="text" name="InstructorCost2" id="InstructorCost2" tabindex="4" /></td>
</tr>
<tr>
<th scope="row">Books</th>
<td><input type="text" name="BooksCost1" id="BooksCost1" tabindex="5" /></td>
<td><input type="text" name="BooksCost2" id="BooksCost2" tabindex="6" /></td>
</tr>
<tr>
<th scope="row">Totals</th>
<td><input type="text" name="TotalsCost1" id="TotalsCost1" tabindex="7" /><span id="TotalsCost1"></span></td>
<td><input type="text" name="TotalsCost2" id="TotalsCost2" tabindex="8" /><span id="TotalsCost2"></span></td>
</tr>
<tr>
<th scope="row">Savings</th>
<td colspan="2"><input type="text" name="Savings" id="Savings" /><span id="Savings"></span></td>
</tr>
</table>
<p>
<input type="button" name="calculate" id="calculate" value="Calculate" />
</p>
<p> </p>
<p> </p>
</form>
<script type="text/javascript">
var btn = document.getElementById('calculate');
btn.onclick = function() {
//get the input values
var ManikinCost1 = parseInt(document.getElementById('ManikinCost1').value);
var ManikinCost2 = parseInt(document.getElementById('ManikinCost2').value);
var InstructorCost1 = parseInt(document.getElementById('InstructorCost1').value);
var InstructorCost2 = parseInt(document.getElementById('InstructorCost2').value);
var BooksCost1 = parseInt(document.getElementById('BooksCost1').value);
var BooksCost2 = parseInt(document.getElementById('BooksCost2').value);
// get the elements to hold the results
var TotalsCost1 = document.getElementById('TotalsCost1');
var TotalsCost2 = document.getElementById('TotalsCost2');
var Savings = document.getElementById('Savings');
// create an empty array to hold error messages
var msg = [];
// check each input value, and add an error message to the array if it's not a number
if (isNaN(ManikinCost2)) {
msg.push('Manikin Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost1)) {
msg.push('Instructor Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost2)) {
msg.push('Instructor Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost1)) {
msg.push('Book Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(ManikinCost1)) {
msg.push('Manikin Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost2)) {
msg.push('Book Cost 2 is not a number');
// the value isn't a number
}
// if the array contains any values, display an error message
if (msg.length > 0) {
TotalsCost1.innerHTML = msg.join(', ');
} else {
TotalsCost1.innerHTML = + (ManikinCost1 + InstructorCost1 + BooksCost1);
TotalsCost2.innerHTML = + (ManikinCost2 + InstructorCost2 + BooksCost2);
Savings.innerHTML = + (TotalsCost1 - TotalsCost2);
}
};
</script>
</body>
btn.onclick = (function(){...})();
You need to put onclick events inside self-calling code, or what are called closures. Move your entire btn.onclick function inside of this bit of code: (...)() in order to make it work.
Good attempt, a few small things wrong but pretty close!
I have made a few changes here.
As mentioned in a comment, I wrapped the function with brackets (function() {...});
I also changed innerHTML to be value as we are updating text inputs, and your savings calculation should be input.value, which I have updated for you.
Let me know how you get on!
<body>
<form id="form1" name="form1" method="post" action="">
<table width="500" border="1">
<tr>
<th scope="col">Item</th>
<th scope="col">Cost 1</th>
<th scope="col">Cost 2</th>
</tr>
<tr>
<th scope="row">Manikin</th>
<td><input type="text" name="ManikinCost1" id="ManikinCost1" tabindex="1" /></td>
<td><input type="text" name="ManikinCost2" id="ManikinCost2" tabindex="2" /></td>
</tr>
<tr>
<th scope="row">Instructor</th>
<td><input type="text" name="InstructorCost1" id="InstructorCost1" tabindex="3" /></td>
<td><input type="text" name="InstructorCost2" id="InstructorCost2" tabindex="4" /></td>
</tr>
<tr>
<th scope="row">Books</th>
<td><input type="text" name="BooksCost1" id="BooksCost1" tabindex="5" /></td>
<td><input type="text" name="BooksCost2" id="BooksCost2" tabindex="6" /></td>
</tr>
<tr>
<th scope="row">Totals</th>
<td><input type="text" name="TotalsCost1" id="TotalsCost1" tabindex="7" /><span id="TotalsCost1"></span></td>
<td><input type="text" name="TotalsCost2" id="TotalsCost2" tabindex="8" /><span id="TotalsCost2"></span></td>
</tr>
<tr>
<th scope="row">Savings</th>
<td colspan="2"><input type="text" name="Savings" id="Savings" /><span id="Savings"></span></td>
</tr>
</table>
<p>
<input type="button" name="calculate" id="calculate" value="Calculate" />
</p>
<p> </p>
<p> </p>
</form>
<script type="text/javascript">
var btn = document.getElementById('calculate');
btn.onclick = (function() {
//get the input values
var ManikinCost1 = parseInt(document.getElementById('ManikinCost1').value);
var ManikinCost2 = parseInt(document.getElementById('ManikinCost2').value);
var InstructorCost1 = parseInt(document.getElementById('InstructorCost1').value);
var InstructorCost2 = parseInt(document.getElementById('InstructorCost2').value);
var BooksCost1 = parseInt(document.getElementById('BooksCost1').value);
var BooksCost2 = parseInt(document.getElementById('BooksCost2').value);
// get the elements to hold the results
var TotalsCost1 = document.getElementById('TotalsCost1');
var TotalsCost2 = document.getElementById('TotalsCost2');
var Savings = document.getElementById('Savings');
// create an empty array to hold error messages
var msg = [];
// check each input value, and add an error message to the array if it's not a number
if (isNaN(ManikinCost2)) {
msg.push('Manikin Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost1)) {
msg.push('Instructor Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost2)) {
msg.push('Instructor Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost1)) {
msg.push('Book Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(ManikinCost1)) {
msg.push('Manikin Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost2)) {
msg.push('Book Cost 2 is not a number');
// the value isn't a number
}
// if the array contains any values, display an error message
if (msg.length > 0) {
TotalsCost1.innerHTML = msg.join(', ');
} else {
TotalsCost1.value = + (ManikinCost1 + InstructorCost1 + BooksCost1);
TotalsCost2.value = + (ManikinCost2 + InstructorCost2 + BooksCost2);
Savings.value = + (TotalsCost1.value - TotalsCost2.value);
}
});
</script>
</body>

Categories