New to Javascript and I can't get the error message ReferenceError: calculateOrder is not defined to go away no matter what I try. I've moved my var out and back in tried different statements. Nothing of the knowledge I have so far is working. How can I get rid of this error message? Would appreciate any help or pointers I can get.
var cost = 750;
var pasta_prices = new Array();
pasta_prices["spaghetti"] = 0;
pasta_prices["fettucine"] = 50;
pasta_prices["fusilli"] = 75;
var sauce_prices = new Array();
sauce_prices["pomodoro"] = 0;
sauce_prices["bolognese"] = 50;
sauce_prices["alfredo"] = 100;
function getPastaPrice() {
var pastaPrice = 0;
var form = document.forms["myForm"];
var selectedPasta = myForm.elements["pastatype"];
for (var i = 0; i < selectedPasta.length; i++) {
if (selectedPasta[i].checked) {
pastaPrice = pasta_prices[selectedPasta[i].value];
break;
}
}
return pastaPrice;
}
function getSaucePrice() {
var saucePrice = 0;
var myForm = document.forms["myForm"];
var selectedSauce = myForm.elements["sauce"];
saucePrice = sauce_prices[selectedSauce.value];
return saucePrice;
}
function extrasPrice() {
var extraPrice = 0;
var myForm = document.forms["myForm"];
var includeSalad = myForm.elements["salad"];
var includeSticks = myForm.elements["sticks"];
if (includeSalad.checked == true) {
extraPrice = 200;
}
if (includeSticks.checked == true) {
extraPrice = 100;
}
return extraPrice;
}
function calculateOrder() {
var ordCost = cost + getPastaPrice() + getSaucePrice() + extrasPrice();
console.log((ordCost / 100).toFixed(2));
return ordCost;
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="description" content="Costello Improved">
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Costellos Pasta and Pizza</title>
<script language="JavaScript" type="text/javascript" src="costello.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<style>
.col-md-12{
text-align: center;
font-size: 3em;
background-color: red;
}
.msg{
text-align:center;
font-size: 1.3em;
color: red;
}
.row{
margin-top: 10px;
border: 5px solid white;
background-color: silver;
padding: 10px;
}
.label{
text-align:center;
vertical-align:top;
}
#submitMessage{
transition: opacity 10s;
}
#cancel{
text-decoration: underline;
}
</style>
</head>
<body>
<form name="myForm" action="https://costello-pasta.glitch.me/order" id="myForm" method="POST" onsubmit="return calculateOrder()">
<div class="container">
<div class="row">
<div class="col-md-12" id="debug">Costello's Online Orders</div>
</div>
<div class="row">
<div class="col-md-4 label">Pasta Bowl</div>
<div class="col-md-4" > (basic price: $7.50)</div>
<div class="col-md-4" ></div>
</div>
<div class="row">
<div class="col-md-4 label">Pasta</div>
<div class="col-md-4" >
<div><input type="radio" name="pastatype" value="0" id="spaghetti"/>Spaghetti (no extra cost)</div>
<div><input type="radio" name="pastatype" value="50" id="fettucine"/>Fettucine (add 50 cents)</div>
<div><input type="radio" name="pastatype" value="75" id="fusilli"/>Fusilli (add 75 cents)</div>
</div>
<div class="col-md-4 msg" id="radioLabel"></div>
</div>
<div class="row">
<div class="col-md-4 label">Sauce</div>
<div class="col-md-4" >
<select name="sauce" >
<option value="0" id="pomodoro">Pomodoro (no extra cost)</option>
<option value="50" id="bolognese">Bolognese (add 50 cents)</option>
<option value="100" id="alfredo">Alfredo (add $1.00)</option>
</select>
</div>
<div class="col-md-4" ></div>
</div>
<div class="row">
<div class="col-md-4 label">Extras</div>
<div class="col-md-4" >
<div><input type="checkbox" name="extras" value="200" id="salad"/>Side salad (add $2.00)</div>
<div><input type="checkbox" name="extras" value="100" id="sticks"/>Bread sticks (add $1.00)</div>
</div>
<div class="col-md-4" ></div>
</div>
<div class="row">
<div class="col-md-4 label">Name</div>
<div class="col-md-4" ><input type="text" id="name" name="client_name" /></div>
<div class="col-md-4 msg" id="nameLabel"></div>
</div>
<div class="row">
<div class="col-md-4 label">Phone</div>
<div class="col-md-4" ><input type="text" id="phone" value="" /></div>
<div class="col-md-4 msg" id="phoneLabel"></div>
</div>
<div class="row">
<div class="col-md-4 label"><input type="submit" value="Order" /></div>
<div class="col-md-4" id="totalcost"></div>
<div class="col-md-4 msg" id="submitMessage"></div>
</div>
</div>
</form>
</body>
</html>
selectedPasta[i].value will give you "0" or "50" accordingly. And they are not present in pastaPrices, hence the return value from getPastaPrice is undefined. Let me modify your jsBin and share the results.
Working JSBin here: https://jsbin.com/qokaboj/edit?html,js,console,output
Here is your working JS code:
enter code here
function getPastaPrice(){
var pastaPrice=0;
var form = document.forms["myForm"];
var selectedPasta = myForm.elements["pastatype"];
for(var i = 0; i < selectedPasta.length; i++) {
if(selectedPasta[i].checked) {
pastaPrice = pasta_prices[selectedPasta[i].id];
break;
}
}
return pastaPrice;
}
function getSaucePrice() {
var saucePrice=0;
var myForm = document.forms["myForm"];
var selectedSauce = myForm.elements["sauce"];
for(var i=0; i<selectedSauce.length; i++){
if(selectedSauce[i].selected){
saucePrice = sauce_prices[selectedSauce[i].id];
break;
}
}
return saucePrice;
}
function extrasPrice() {
var extraPrice=0;
var myForm = document.forms["myForm"];
var includeSalad = myForm.elements["salad"];
var includeSticks = myForm.elements["sticks"];
if(includeSalad.checked) {
extraPrice = 200;
}
if (includeSticks.checked) {
extraPrice += 100;
}
return extraPrice;
}
function calculateOrder() {
var ordCost = cost + getPastaPrice() + getSaucePrice() + extrasPrice();
console.log((ordCost/100).toFixed(2));
return calculateOrder;
}
the calculateOrder function is attempting to return itself:
function calculateOrder() {
[...]
return calculateOrder;
}
This might help
You created a function called calculateOrder
function calculateOrder() {
var ordCost = cost + getPastaPrice() + getSaucePrice() + extrasPrice();
console.log((ordCost / 100).toFixed(2));
return calculateOrder; // <--- problem here.
}
Instead of returning calculateOreder you should return ordCost.
How will this help? Well we can do some checks in your function to see that calculateOrder is...not defined! The calculateOrder that is not defined is that undefined variable I noted up there.
Go ahead a try this in your code too to see what is and is not defined in your function
function calculateOrder() {
var ordCost = cost + getPastaPrice() + getSaucePrice() + extrasPrice();
console.log((ordCost / 100).toFixed(2));
console.log('calculateOrder: ', calculateOrder);
console.log('ordCost', ordCost)
return ordCost; //<--- the value you might be looking for
}
Related
[I'm simply trying to make a form that allows you to select which box the user's name and password will display in. The code I have works fine but I'm curious to see how it could be refactored to be less repetitive. I thought of using a JS object but I'm not sure how to go about that in this instance. Any help would be appreciated! Here is a link to the CodePen: (https://codepen.io/TOOTCODER/pen/yLeagRq)
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Which Box?</title>
<style>
.square{
border: 1px solid black;
width: 15rem;
height: 15rem;
float: left;
}
#formContainer {
position: relative;
top: 16rem;
left: -45.5rem;
}
.boxTitle {
text-align: center;
margin-top: 1em;
}
.boxOutputContainer {
text-align: center;
}
</style>
</head>
<body>
<div class="square">
<h1 class="boxTitle">BOX1</h1>
<div class="boxOutputContainer">
<div id="b1NameOutput"></div>
<div id="b1PasswordOutput"></div>
</div>
</div>
<div class="square">
<h1 class="boxTitle">BOX2</h1>
<div class="boxOutputContainer">
<div id="b2NameOutput"></div>
<div id="b2PasswordOutput"></div>
</div>
</div>
<div class="square">
<h1 class="boxTitle">BOX3</h1>
<div class="boxOutputContainer">
<div id="b3NameOutput"></div>
<div id="b3PasswordOutput"></div>
</div>
</div>
<div id="formContainer">
<form>
<label for="name">Name:</label>
<input required type="text" id="name">
<label for="name">Password:</label>
<input required type="text" id="password">
<label for="boxSelect">Which box?</label>
<select id="boxSelect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="submit" id="submitBtn">
</form>
</div>
<script>
var submitBtn = document.querySelector("#submitBtn");
var resetBtn = document.querySelector("#resetBtn");
submitBtn.addEventListener("click", function(){
event.preventDefault();
var name = document.querySelector("#name");
var password = document.querySelector("#password");
var boxSelect = document.querySelector("#boxSelect");
var b1NameOutput = document.querySelector("#b1NameOutput");
var b1PasswordOutput = document.querySelector("#b1PasswordOutput");
var b2NameOutput = document.querySelector("#b2NameOutput");
var b2PasswordOutput = document.querySelector("#b2PasswordOutput");
var b3NameOutput = document.querySelector("#b3NameOutput");
var b3PasswordOutput = document.querySelector("#b3PasswordOutput");
if(boxSelect.value == 1){
b1NameOutput.innerHTML = "<p>"+name.value+"</p>";
b1PasswordOutput.innerHTML = "<p>"+password.value+"</p>";
}else if(boxSelect.value == 2){
b2NameOutput.innerHTML = "<p>"+name.value+"</p>";
b2PasswordOutput.innerHTML = "<p>"+password.value+"</p>";
}else if(boxSelect.value == 3){
b3NameOutput.innerHTML = "<p>"+name.value+"</p>";
b3PasswordOutput.innerHTML = "<p>"+password.value+"</p>";
}});
</script>
</body>
</html>
I see someone beat me to the answer but here is another option that is easy to refactor.
var submitBtn = document.querySelector("#submitBtn");
var resetBtn = document.querySelector("#resetBtn");
submitBtn.addEventListener("click", function(){
event.preventDefault();
var name = document.querySelector("#name");
var password = document.querySelector("#password");
var boxSelect = document.querySelector("#boxSelect");
var nameId = `#b${boxSelect.value}NameOutput`;
var passwordId = `#b${boxSelect.value}PasswordOutput`;
var nameOutput = document.querySelector(nameId);
nameOutput.innerHTML = "<p>"+name.value+"</p>";
var passwordOutput = document.querySelector(passwordId);
passwordOutput.innerHTML = "<p>"+password.value+"</p>";
});
I am trying to add Back buton to my existing Script without success so far. I like this script because it also has a Validation process. I tried another code that has Previous button working, but no validation which made my project useless..
Here is my Javascript code below:
<script>
//Validation & Steps
$(document).ready(function ()
{
var navListItems = $('div.setup-panel div a');
allWells = $('.setup-content');
allNextBtn = $('.nextBtn');
allPrevBtn = $('.prevBtn');
allWells.hide();
navListItems.click(function (e) {
e.preventDefault();
var $target = $($(this).attr('href'));
$item = $(this);
if (!$item.hasClass('disabled')) {
navListItems.removeClass('btn-success').addClass('btn-default');
$item.addClass('btn-success');
allWells.hide();
$target.show();
$target.find('input:eq(0)').focus();
}
});
allNextBtn.click(function ()
{
var curStep = $(this).closest(".setup-content");
curStepBtn = curStep.attr("id");
nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn +
'"]').parent().next().children("a");
curInputs = curStep.find("input[type='url'],input[type='checkbox'],input[type='text'],input[type='email'],input[type='radio']"); //
isValid = true;
$(".form-group").removeClass("has-error");
for (var i = 0; i < curInputs.length; i++)
{
if (!curInputs[i].validity.valid)
{
isValid = false;
$(curInputs[i]).closest(".form-group").addClass("has-error");
}
}
if (isValid) nextStepWizard.removeAttr('disabled').trigger('click');
});
// Back button click action
allPrevBtn.click(function()
{
curStepBtn = curStep.attr("id");
curStep = curStep - 2;
allPrevBtn.trigger('click');
nextStepWizard.removeAttr('disabled').trigger('click');
allWells.hide();
})
$('div.setup-panel div a.btn-success').trigger('click');
});
</script>
I was returned to source of your code, this is full code with back button:
<html >
<head>
<meta charset="utf-8"/>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<style>
body{
margin-top:40px;
}
.stepwizard-step p {
margin-top: 10px;
}
.stepwizard-row {
display: table-row;
}
.stepwizard {
display: table;
width: 100%;
position: relative;
}
.stepwizard-step button[disabled] {
opacity: 1 !important;
filter: alpha(opacity=100) !important;
}
.stepwizard-row:before {
top: 14px;
bottom: 0;
position: absolute;
content: " ";
width: 100%;
height: 1px;
background-color: #ccc;
z-order: 0;
}
.stepwizard-step {
display: table-cell;
text-align: center;
position: relative;
}
.btn-circle {
width: 30px;
height: 30px;
text-align: center;
padding: 6px 0;
font-size: 12px;
line-height: 1.428571429;
border-radius: 15px;
}
</style>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {
var navListItems = $('div.setup-panel div a'),
allWells = $('.setup-content'),
allNextBtn = $('.nextBtn'),
allPrevBtn = $('.prevBtn');
allWells.hide();
navListItems.click(function (e) {
e.preventDefault();
var $target = $($(this).attr('href')),
$item = $(this);
if (!$item.hasClass('disabled')) {
navListItems.removeClass('btn-primary').addClass('btn-default');
$item.addClass('btn-primary');
allWells.hide();
$target.show();
$target.find('input:eq(0)').focus();
}
});
allNextBtn.click(function(){
var curStep = $(this).closest(".setup-content"),
curStepBtn = curStep.attr("id"),
nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().next().children("a"),
curInputs = curStep.find("input[type='text'],input[type='url']"),
isValid = true;
$(".form-group").removeClass("has-error");
for(var i=0; i<curInputs.length; i++){
if (!curInputs[i].validity.valid){
isValid = false;
$(curInputs[i]).closest(".form-group").addClass("has-error");
}
}
if (isValid)
nextStepWizard.removeAttr('disabled').trigger('click');
});
allPrevBtn.click(function(){
var curStep = $(this).closest(".setup-content"),
curStepBtn = curStep.attr("id"),
prevStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().prev().children("a");
prevStepWizard.removeAttr('disabled').trigger('click');
});
$('div.setup-panel div a.btn-primary').trigger('click');
});
</script>
</head>
<body>
<div class="container">
<div class="stepwizard">
<div class="stepwizard-row setup-panel">
<div class="stepwizard-step">
1
<p>Step 1</p>
</div>
<div class="stepwizard-step">
2
<p>Step 2</p>
</div>
<div class="stepwizard-step">
3
<p>Step 3</p>
</div>
</div>
</div>
<form role="form">
<div class="row setup-content" id="step-1">
<div class="col-xs-12">
<div class="col-md-12">
<h3> Step 1</h3>
<div class="form-group">
<label class="control-label">First Name</label>
<input maxlength="100" type="text" required="required" class="form-control" placeholder="Enter First Name" />
</div>
<div class="form-group">
<label class="control-label">Last Name</label>
<input maxlength="100" type="text" required="required" class="form-control" placeholder="Enter Last Name" />
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-2">
<div class="col-xs-12">
<div class="col-md-12">
<h3> Step 2</h3>
<div class="form-group">
<label class="control-label">Company Name</label>
<input maxlength="200" type="text" required="required" class="form-control" placeholder="Enter Company Name" />
</div>
<div class="form-group">
<label class="control-label">Company Address</label>
<input maxlength="200" type="text" required="required" class="form-control" placeholder="Enter Company Address" />
</div>
<button class="btn btn-warning prevBtn btn-lg pull-left" type="button" >Back</button>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-3">
<div class="col-xs-12">
<div class="col-md-12">
<h3> Step 3</h3>
<button class="btn btn-success btn-lg pull-right" type="submit">Finish!</button>
</div>
</div>
</div>
</form>
</div>
</body>
</html>
jQuery previous button not working as expected.
Basically the best way to explain it is if I'm on question 5 and I click the previous button, it defaults to question 1 rather than going to question 4.
So it's defaulting to question 1... That's a problem.
What to do?
jQuery is in the bottom in script tags.
if (i.Question_Type == "DROPDOWN")
{
<div class="container text-center">
<div class="row idrow" data-questions="#counter">
#{
counter++;
}
<div id="question1" class="form-group">
<label class="lab text-center" for="form-group-select">
#i.Question_Order #Html.Raw(#i.Question)
</label>
<select class="form-control" id="form-group-select">
#for (int x = 1; x <= Convert.ToInt32(i.Question_SubType); x++)
{
var t = x - 1;
if (i.qOps != null)
{
<option> #i.qOps.options[t]</option>
}
else
{
<option> #x</option>
}
}
</select>
</div>
</div>
</div>
}
if (i.Question_Type == "RADIO")
{
<div class="container">
<div class="row idrow" data-questions="#counter">
#{counter++;
}
<div class="form-group">
<label class="lab" for="questions">
#i.Question_Order #i.Question
</label>
<div class="row">
<div class="col-xs-12">
<div id="question1" class="radio-inline">
#for (int x = 1; x <= Convert.ToInt32(i.Question_SubType); x++)
{
var t = x - 1;
if (i.qOps != null)
{
<label class="radio-inline"><input type="radio" name="question"> #i.qOps.options[t]</label>
}
else
{
<label class="radio-inline"><input type="radio" min="0" max="#x" name="question"></label>
}
}
</div>
</div>
</div>
</div>
</div>
</div>
}
if (i.Question_Type == "CHECKBOX")
{
for (int y = 1; y <= Convert.ToInt32(i.Question_SubType); y++)
{
#*<div class="container">
<div class="row">
<label>#y</label> <input type="checkbox" name="question">
</div>
</div>*#
}
}
}
<div class="azibsButtons">
<button type="button" id="previous" class="btn btn-primary pull-left">Prev</button>
<button type="button" id="next" class="btn btn-primary pull-right">Next</button>
</div>
<script>
$(document).ready(function () {
$(".idrow").each(function (i) {
var inner = $(this).data('questions');
if (inner == 0) {
$(this).removeClass('hidden');
} else {
$(this).addClass('hidden');
}
});
$("#next").click(function () {
$(".idrow").each(function (i) {
var inp = $(this);
if (!inp.hasClass('hidden')) {
var dataVal = inp.data("questions");
dataVal++;
inp.addClass('hidden');
$('[data-questions=' + dataVal + ']').removeClass('hidden');
return false;
}
});
$("#previous").click(function () {
$(".idrow").each(function (i) {
var inp = $(this);
if (!inp.hasClass('hidden')) {
var dataVal = inp.data("questions");
dataVal--;
inp.addClass('hidden');
$('[data-questions=' + dataVal + ']').removeClass('hidden');
return false;
}
});
});
});
});
</script>
Hey guys I got the solution Thanks to Daniel.
The next event closing braces were wrapped around the previous event, which caused the problem to default to question 1 when clicked previous.
$("#next").click(function () {
$(".idrow").each(function (i) {
var inp = $(this);
if (!inp.hasClass('hidden')) {
var dataVal = inp.data("questions");
dataVal++;
inp.addClass('hidden');
$('[data-questions=' + dataVal + ']').removeClass('hidden');
return false;
}
});
});
$("#previous").click(function () {
$(".idrow").each(function (i) {
var inp = $(this);
if (!inp.hasClass('hidden')) {
var dataVal = inp.data("questions");
dataVal--;
inp.addClass('hidden');
$('[data-questions=' + dataVal + ']').removeClass('hidden');
return false;
}
});
});
I have converted a csv to JSON object and have populated it on a html table. Rest of the columns are fine but the last column of the table shows 'Undefined'. CSV file -
The table displayed as-
What is the problem here?
HTML file-
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html>
<head>
<title>Japan Automation</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"> </script>
<!--<script type="text/javascript" src="JavaScript.js"></script>-->
<script type="text/javascript" src="JavaScript4.js"></script>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
th {
text-align: left;
}
table {
border-spacing: 5px;
}
.guide {
text-decoration: underline;
text-align: center;
}
.odd {
color: #fff;
background: #666;
}
.even {
color: #666;
}
.hot {
border: 1px solid #f00;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<h2>Global Order Visibility</h2>
</div>
<div class="panel panel-primary">
<div class="panel-heading">Japan Automation Tool</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-12 col-sm-offset-1">
<form id="form1" runat="server" class="form-horizontal">
<div class="form-group">
<div class="col-sm-5">
<div class="col-sm-6">
<input type="file" accept=".csv" id="fileUpload" />
</div>
<div class="col-sm-6">
<input type="button" id="upload" class="btn btn-primary" value="Upload" />
</div>
</div>
<div class="col-sm-7">
<div class="col-sm-2">
<input type="button" id="cancel" class="btn btn-primary btn pull-right" value="Cancel/Save" style="visibility: hidden" />
</div>
<div class="col-sm-2">
<input type="button" id="process" class="btn btn-primary btn pull-right" value="Process" style="visibility: hidden" />
</div>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="panel panel-default" style="align-self: center">
<div class="panel-body" style="max-height: 400px; min-height: 400px; overflow-y: scroll;">
<div class="row">
<div class="col-sm-12">
<center>
<div class="input-append" id="filterDev" style="visibility:hidden">
<input name="search" id="inputFilter" placeholder="Enter ID to filter" />
<input type="button" value="Filter" id="filter" class="btn btn-primary" />
</div></center>
</div>
<br />
<br />
</div>
<div class="row">
<div class="col-sm-12" id="dvCSV">
<table id="my-table">
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p id="download" style="color: cornflowerblue; visibility: hidden"><strong>Please click the below links to download the processed file..</strong></p>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="col-sm-3">
<p id="File1" style="color: cornflowerblue; text-decoration: underline; visibility: hidden">File1 Download</p>
</div>
<div class="col-sm-3">
<p id="File2" style="color: cornflowerblue; text-decoration: underline; visibility: hidden">File2 Download</p>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$("#cancel").on("click", function () {
$('input:checked').each(function () {
$(this).closest("tr").remove();
});
});
$(function () {
$("#process").bind("click", function () {
document.getElementById("File1").style.visibility = "visible";
document.getElementById("File2").style.visibility = "visible";
document.getElementById("download").style.visibility = "visible";
});
});
$("#filter").click(function () {
ids = $("#inputFilter").val();
if (ids != "") {
idsArray = ids.split(",");
$("#my-table tr:gt(0)").hide();
$.each(idsArray, function (i, v) {
$("#my-table tr[data-id=" + v + "]").show();
})
} else {
$("#my-table tr").show();
}
});
</script>
JavaScript4.js
$(function () {
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
//var table = $("<table id='name'/>");
var lines = e.target.result.split("\n");
var result = [];
var headers = lines[0].split(",");
//alert(headers);
for (var i = 1; i < lines.length; i++) {
var obj = {};
var currentline = lines[i].split(",");
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
populateTable(result);
document.getElementById("cancel").style.visibility = "visible";
document.getElementById("process").style.visibility = "visible";
document.getElementById("filterDev").style.visibility = "visible";
}
reader.readAsText($("#fileUpload")[0].files[0]);
}
}
});
});
$(function () {
$("#process").bind("click", function () {
document.getElementById("File1").style.visibility = "visible";
document.getElementById("File2").style.visibility = "visible";
});
});
function populateTable(finalObject) {
var obj = finalObject;
var table = $("<table id='my-table' />");
table[0].border = "1";
var columns = Object.keys(obj[0]);
var columnCount = columns.length;
var row = $(table[0].insertRow(-1));
for (var i = 0; i < columnCount; i++) {
var headerCell = $("<th />");
headerCell.html([columns[i]]);
row.append(headerCell);
}
$.each(obj, function (i, obj) {
//row = '<tr data-id="' + obj.ID + '"><td>' + obj.ID + '</td><td>' + obj.NAME + '</td><td>' + obj.CITY + '</td><td>' + obj.ADDRESS + '</td></tr>';
row = '<tr data-id="' + obj.ID + '"><td>' + obj.ID + '</td><td>' + obj.NAME + '</td><td>' + obj.CITY + '</td><td>' + obj.ADDRESS + '</td></tr>';
table.append(row);
});
var dvTable = $("#dvCSV");
dvTable.html("");
dvTable.append(table);
}
UPDATE ...
Line breaks where messing up with the ADDRESS property. Just remove all line breaks before using the strings and you will be fine:
var headers = lines[0].split(",");
for (var i = 1; i < headers.length; i++) {
var header = headers[i];
header = header.replace(/(\r\n|\n|\r)/gm,"");
headers[i] = header;
}
DEMO: http://jsbin.com/hatasaf/3/edit?js,output
I really could not find out why the ADDRESS property was being wrapped around quotes and being inaccessible, but an array fixed the problem ...
I'll investigate more to isolate the issue but for your purposes just use the code in the demo http://jsbin.com/hatasaf/2/edit?js,output
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var lines = e.target.result.split("\n");
var result = [];
for (var i = 0; i < lines.length; i++) {
var arr = [];
var currentline = lines[i].split(",");
for (var j = 0; j < currentline.length; j++) {
arr.push(currentline[j]);
}
result.push(arr);
}
populateTable(result);
document.getElementById("cancel").style.visibility = "visible";
document.getElementById("process").style.visibility = "visible";
document.getElementById("filterDev").style.visibility = "visible";
}
reader.readAsText($("#fileUpload")[0].files[0]);
}
}
});
function populateTable(finalArray) {
var table = $("<table id='my-table' />");
table[0].border = "1";
var columns = finalArray[0];
var columnCount = columns.length;
var row = $(table[0].insertRow(-1));
for (var j = 0; j < columns.length; j++) {
var headerCell = $("<th>").text([columns[j]]);
row.append(headerCell);
}
for (var i = 1; i < finalArray.length; i++) {
var item = finalArray[i];
row = '<tr data-id="' + item[0] + '"><td>' + item[0] + '</td><td>' + item[1] + '</td><td>' + item[2] + '</td><td>' + item[3] + '</td></tr>';
table.append(row);
};
var dvTable = $("#dvCSV");
dvTable.html("");
dvTable.append(table);
}
I've read a lot about uncaught reference errors here and think I have the idea down - when the script is trying to call a function or reference a variable that hasn't been initialized yet. However, I am uncertain how to fix this, and why in my case one function works and the other doesn't.
I have one JS file with two functions in it, and one HTML file with a form. The form calls function1 onSubmit, and that works fine. A radio button inside of the form calls function2 onClick, and that's when I get the error:
Uncaught ReferenceError: toggleGender is not defined onclick # forms.html:20
Why would my first function work and not the second? It seems to me like they are operating under the same premise.
function calculatePFT()
{
var userForm = document.getElementById('userValues');
var pullups = userForm.userPullups.value;
var crunches = userForm.userCrunches.value;
var runMinutes = userForm.userMinutes.value;
var runSeconds = userForm.userSeconds.value;
var runScore = 0;
if(runMinutes < 18) { runScore = 100; }
else
{
var minDiff = runMinutes - 18;
var minPoints = minDiff * 6;
var secPoints = Math.ceil(runSeconds/10);
runScore = 100 - (minPoints + secPoints);
}
var score = parseInt(pullups*5) + parseInt(crunches) + parseInt(runScore);
document.getElementById('scoreBox').innerHTML = "You scored " + pullups + " pullups and " + crunches + " crunches and a run time of " + runMinutes + " minutes " + runSeconds + " seconds. TOTAL SCORE: " + score;
}
function toggleGender(var gender)
{
alert("Inside");
var maleForm = document.getElementById('male');
var femaleForm = document.getElementById('female');
if(gender == "f")
{
alert("Female");
maleForm.style.display = 'none';
femaleForm.style.display = 'block';
}
else
{
alert("Male");
maleForm.style.display = 'block';
femaleForm.style.display = 'none';
}
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Javascript Testing</title>
<link rel="stylesheet" href="style.css" />
<script src="scripts.js"></script>
</head>
<body>
<section id="wrapper">
<h3>PFT Calculator</h3>
<form action="#" id="userValues" method="post" onSubmit="calculatePFT()">
<div id="gender">
<span class="maleFemale">Male <input type="radio" name="maleFemale" value="male" CHECKED onClick="toggleGender('m')" /></span>
<span class="maleFemale">Female <input type="radio" name="maleFemale" value="female" onClick="toggleGender('f')" /></span>
</div>
<div id="male">
<div class="scoreLine">
<div class="label">Pullups:</div>
<div class="entry"><input type="number" name="userPullups" min="0" max="20" default="18" class="scoreEntry" required /></div>
</div>
</div>
<div id="female">
<div class="scoreLine">
<div class="label">Hang:</div>
<div class="entry"><input type="number" name="userHang" min="0" max="150" default="70" class="scoreEntry" required /></div>
</div>
</div>
<div class="scoreLine">
<div class="label">Crunches:</div>
<div class="entry"><input type="number" name ="userCrunches" min="0" max="100" default="100" class="scoreEntry" required /></div>
</div>
<div class="scoreLine">
<div class="label">Run (Minutes):</div>
<div class="entry"><input type="number" name="userMinutes" min="0" max="100" default="19" class="scoreEntry" required /></div>
</div>
<div class="scoreLine">
<div class="label">Run (Seconds):</div>
<div class="entry"><input type="number" name="userSeconds" min="0" max="59" default="30" class="scoreEntry" required /></div>
</div>
<div style="text-align:center;"><input type="submit" value="Calculate Score!" id="submitButton" /></div>
</form>
<span id="scoreBox"></span>
</section>
</body>
</html>
function toggleGender(var gender)
You have a syntax error here. Argument names should not be prefixed by var. This causes the functional declaration to fail (hence why you get a reference error when you try to call it).
function calculatePFT()
{
var userForm = document.getElementById('userValues');
var pullups = userForm.userPullups.value;
var crunches = userForm.userCrunches.value;
var runMinutes = userForm.userMinutes.value;
var runSeconds = userForm.userSeconds.value;
var runScore = 0;
if(runMinutes < 18) { runScore = 100; }
else
{
var minDiff = runMinutes - 18;
var minPoints = minDiff * 6;
var secPoints = Math.ceil(runSeconds/10);
runScore = 100 - (minPoints + secPoints);
}
var score = parseInt(pullups*5) + parseInt(crunches) + parseInt(runScore);
document.getElementById('scoreBox').innerHTML = "You scored " + pullups + " pullups and " + crunches + " crunches and a run time of " + runMinutes + " minutes " + runSeconds + " seconds. TOTAL SCORE: " + score;
}
function toggleGender(gender)
{
alert("Inside");
var maleForm = document.getElementById('male');
var femaleForm = document.getElementById('female');
if(gender == "f")
{
alert("Female");
maleForm.style.display = 'none';
femaleForm.style.display = 'block';
}
else
{
alert("Male");
maleForm.style.display = 'block';
femaleForm.style.display = 'none';
}
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Javascript Testing</title>
<link rel="stylesheet" href="style.css" />
<script src="scripts.js"></script>
</head>
<body>
<section id="wrapper">
<h3>PFT Calculator</h3>
<form action="#" id="userValues" method="post" onSubmit="calculatePFT()">
<div id="gender">
<span class="maleFemale">Male <input type="radio" name="maleFemale" value="male" CHECKED onClick="toggleGender('m')" /></span>
<span class="maleFemale">Female <input type="radio" name="maleFemale" value="female" onClick="toggleGender('f')" /></span>
</div>
<div id="male">
<div class="scoreLine">
<div class="label">Pullups:</div>
<div class="entry"><input type="number" name="userPullups" min="0" max="20" default="18" class="scoreEntry" required /></div>
</div>
</div>
<div id="female">
<div class="scoreLine">
<div class="label">Hang:</div>
<div class="entry"><input type="number" name="userHang" min="0" max="150" default="70" class="scoreEntry" required /></div>
</div>
</div>
<div class="scoreLine">
<div class="label">Crunches:</div>
<div class="entry"><input type="number" name ="userCrunches" min="0" max="100" default="100" class="scoreEntry" required /></div>
</div>
<div class="scoreLine">
<div class="label">Run (Minutes):</div>
<div class="entry"><input type="number" name="userMinutes" min="0" max="100" default="19" class="scoreEntry" required /></div>
</div>
<div class="scoreLine">
<div class="label">Run (Seconds):</div>
<div class="entry"><input type="number" name="userSeconds" min="0" max="59" default="30" class="scoreEntry" required /></div>
</div>
<div style="text-align:center;"><input type="submit" value="Calculate Score!" id="submitButton" /></div>
</form>
<span id="scoreBox"></span>
</section>
</body>
</html>