Javascript Recipe Calculator, Hangs on isNan() Function? - javascript

I'm making a recipe calculator for my coursework. I have reached the stage where it will correctly validate everything and make a new row in a table. Sadly in the if statement within the recipe function, it always goes true for isNaN? No matter what I put? Can anyone help me with this?
<!DOCTYPE html>
<html>
<head>
<title>Website Title</title>
<script type="text/javascript">
// Declare all variables
var ingredient = document.getElementById("ingredient").value;
var amount = document.getElementById("number").value;
var unit = document.getElementById("unit").value;
var ingredientcount = 0
// The save function
function save(){
var verified = true;
while(verified){
var name = prompt("What's the name of the recipe?")
var serves = prompt("How many people does it serve?")
if(serves === "" || name === "" || isNaN(serves)=== true)
{
alert("You have to enter a name, followed by the number of people it serves. Try again.")
verified = false;
}
else{
alert("sucess!");
// array(ingredient,amount,unit,name,serves)
return;
}
}
}
// The function to valiate the data and manage everything
function recipe(){
if(ingredient === ""|| amount === "" || unit === "Select Unit"){
alert("You must fill in all fields.")
}
else if(isNaN(amount)){
alert("You have to enter a number in the amount field")
}
else{
alert("hey!")
alert(recipe[1][2] + recipe[1][1])
var totalamount = amount + " "+ unit
insRow(ingredient, totalamount) // post(0,*123456*,"Fish")
ingredientcount ++;
alert(ingredientcount);
}
}
</script>
</head>
<body>
<h1>Recipe Name</h1>
<h2>Serves many people </h2>
<table border="1" id="table" >
<tr>
<td>
<input type="text" id="ingredient" placeholder="Enter an Ingredient">
</td>
<td>
<input type="text" id="number" placeholder="Enter an amount">
<select id="unit">
<option>Select Unit</option>
<option>Grams</option>
<option>Mililitres</option>
<option>Number</option>
</select>
</td>
<td>
<button type="button" onclick="recipe()">Add</button>
<button type="button" onclick="save()">Save</button>
</td>
</tr>
<th>Ingredient</th>
<th>Amount</th>
<th> </th>
</table>
</body>
</html>

The problem is that you are setting the values of ingredient, amount, and unit when the page loads, not when the Add button is pushed. You need to move those assignments to the recipe() function.

Related

How to find the area of the triangle using basic codes such like:

Hi guys im a grade 10 student and was asked to create a basic like calculator to solve for the area of the triangle, but i really dont know how.I can do it with the use of a radio button but my teacher said to do it without the radio input. My codes works fine but if i press clear and input a value to the base and height, it will say syntax error...please can you help me? also whenever i dont put a value on base and height,it says 0 instead of syntax error,so please help me....(also sorry about earlier, im just new to this site)
this is my code:
<html>
<head>
<title>hfsabfhsabfihs</title>
</head>
<body>
<script type="text/javascript">
<!--
function checkbutton() {
var num1 = document.getElementById("input1").value;
var num2 = document.getElementById("input2").value;
if (document.form1.checked == false) {
alert("Syntax Error")
} else {
alert(num1 * num2 / 2);
}
}
function clearbutton() {
document.form1.checked = false;
var num1 = document.getElementById("input1").value = "";
var num2 = document.getElementById("input2").value = "";
}
//-->
</script>
<form name="form1">
<table>
<tr>
<td>Base</td>
<td><input type="text" id="input1" /></td>
</tr>
<tr>
<td>Height</td>
<td><input type="text" id="input2" /></td>
</tr>
</table>
<input type="button" value="Compute" onclick="checkbutton()">
<input type="button" value="Clear" onclick="clearbutton()">
</body>
</html>
problem is on clear function function
function clearbutton()
{
// document.form1.checked= false;
var num1 = document.getElementById("input1").value="";
var num2 = document.getElementById("input2").value="";
}
you are getting this error because you have set a variable here i.e form1.checked. either remove this variable or change its value on calculation function
Hope the below code helps:
// vairbale
const baseInput = document.querySelector("#input1")
const heightInput = document.querySelector("#input2")
const coputeBTn = document.querySelector("#Compute")
const areaTriangle = (base, height) =>{
let total =""
let error = false
let errorMessage = ""
if(base != "" && height != ""){
error = false
total = base * height / 2
}else{
error = true
errorMessage = "Please fill all inputs."
return errorMessage
}
return total
}
// Calling Function
coputeBTn.addEventListener("click", ()=>{
console.log(areaTriangle(Number(baseInput.value), Number(heightInput.value)))
})
<!doctype HTML>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form name="form1">
<table>
<tr>
<td>Base</td>
<td><input type="text" id="input1" /></td>
</tr>
<tr>
<td>Height</td>
<td><input type="text" id="input2" /></td>
</tr>
</table>
<input type="button" id="Compute" value="Compute">
<input type="button" value="Clear" onclick="clearbutton()">
</form>
</body>
</html>

Delete array graphically in Javascript

I'm having trouble figuring out how to do this, and well, need help.
I'm trying to put my information into an array that's going to be shown and always be able to grow. I need help deleting specific entries into it, either by searching for one or by pointing a mouse and deleting it,
Is there any nice easy way to do it?
<!doctype html>
<html lang="sv">
<body>
<head>
<meta charset="UTF-8">
</title>
</head>
<body>
<input type="text" placeholder="Förnamn" id="name" autofocus>
<input type="date" id="pnummer" autofocus>
<input type="text" placeholder="Efternamn" id="enamn" autofocus>
<input type="button" value="mata in" onclick="register()">
<input type="button" value="visa" onclick="show()">
<script type="text/javascript">
array=[]
function register()
{
var fnamn = document.getElementById("name").value;
var enamn = document.getElementById("enamn").value;
var pnummer = document.getElementById("pnummer").value;
var p1 = new Person(fnamn,pnummer,enamn);
array.push(p1);
}
function Person(fnamn, pnummer, enamn)
{
this.fnamn=fnamn;
this.pnummer=pnummer;
this.enamn=enamn;
this.visa=function()
{
var panel ="Förnamn:"+" "+this.fnamn+" "+"Efternamn:"+" "+this.enamn+" "+"Personnummer:"+" "+this.pnummer+"<br>";
return panel;
}
}
function show(){
var showperson=document.getElementById("new");
showperson.innerHTML="";
var i=0;
while (array.length>i)
{
showperson.innerHTML+=array[i].visa()
i++;
}
}
</script>
<p id="new"></p>
<div id="panel"></div>
</body>
</html>
I am not 100% sure what you're trying to do or what some of those words mean but is this what you're trying to do?
var peopleTracker = {};
var peopleCounter = 0;
function addPerson()
{
// get the values
var firstName = document.getElementById("firstName").value.trim();
var lastName = document.getElementById("lastName").value.trim();
var birthday = document.getElementById("birthday").value.trim();
// make sure none are blank
if(firstName == "" || lastName == "" || birthday == "") return;
// give each person an ID so we can remove them later
var personID = ++peopleCounter;
peopleTracker[personID] = {
"firstName" : firstName,
"lastName" : lastName,
"birthday" : birthday
};
// add the person to the table
var row = document.getElementById("peopleList").insertRow();
row.insertCell().innerText = firstName;
row.insertCell().innerText = lastName;
row.insertCell().innerText = birthday;
row.insertCell().innerHTML = 'remove';
}
// delete a user from the tracker and remove the row
function removePerson(row, personID)
{
delete peopleTracker[personID];
row.parentNode.removeChild(row);
}
<!doctype html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<title>the dingo ate my baby</title>
</head>
<body>
<input type="text" placeholder="First Name" id="firstName" autofocus>
<input type="text" placeholder="Sur Name" id="lastName" autofocus>
<input type="date" id="birthday" autofocus>
<input type="button" value="Add Person" onclick="addPerson()">
<br /><br />
<table border="1">
<thead>
<tr>
<th>First Name</th>
<th>Sur Name</th>
<th>Birthday</th>
<th>Action</th>
</tr>
</thead>
<tbody id="peopleList"></tbody>
</table>
</body>
</html>
A few thoughts:
If you're going to use an array to delete then you're going to need to use some unique ID to be able to find the person you want to delete. You cannot use the array index because that will change as you remove people from the array.
By using an object to store the users you can delete by using a unique ID that changes for each user added.
I jQuery is an option, you could find the index of your clicked <div> and delete the element with something like the following function:
$( "div.someIdYouGiveIt" ).click(function() {
var index = $( "div.someClassYouGiveIt" ).index( this );
array.splice(index, 1);
});

JavaScript how to use for each

<!DOCTYPE html>
<html>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0" id="errorTable" class="alert alert-danger alert-warning">
<!-- Validating City START -->
<div id="divname">
<tr>
<td width="3"></td>
<td width="23"><span class="table_row_error_text"><img id="imgsum" src="/images/error.gif" class="image" style="display: none;" ></span> </td>
<td width="5"></td>
<td><span class="table_row_error_text"> <span id="errorsum" /></span> </td>
</tr>
</div>
<!-- Validating City ENDS -->
<!-- Validating Zip Code START -->
<div id="divtype">
<tr>
<td width="3"></td>
<td width="23"><span class="table_row_error_text"><img id="imgdesc" src="/images/error.gif" class="image" style="display: none;" ></span> </td>
<td width="5"></td>
<td><span class="table_row_error_text"> <span id="errordesc" /></span> </td>
</tr>
</div>
<!-- Validating Zip Code ENDS -->
</table> Summary:
<input id="summaryOfAlert" type="text" />
<br>
<br> Description:
<input id="textarea3" type="text" />
<br>
<br> Save:
<input type="submit" onClick="return validateText()" /> </body>
<script>
function validateText() {
alert("Hi");
var summary = document.getElementById("summaryOfAlert").value;
var description = document.getElementById("textarea3").value;
var letters = /^[A-Za-z0-9._\-,\s]+$/;
var j;
j = 0;
if (summary != "") {
if (!summary.match(letters)) {
document.getElementById('errorsum').innerHTML = "In Summary Please Enter Only A-Za-z0-9-,_.";
document.getElementById("divname").style.display = 'block';
document.getElementById("imgsum").style.display = 'block';
j++;
}
}
if (description != "") {
if (!description.match(letters)) {
document.getElementById('errordesc').innerHTML = "In Description Please Enter Only A-Za-z0-9-,_.";
document.getElementById("divtype").style.display = 'block';
document.getElementById("imgdesc").style.display = 'block';
j++;
}
}
if (j == 0) {
return true;
} else return false;
}
</script>
</html>
Above is a html/javascript code which I have developed for front end validation for special characters. it is working fine but my problem is whenever I entered special chars like <>%&(^ in both text fields and after submitting it is showing error message like as shown
In Summary Please Enter Only A-Za-z0-9-,.
In Description Please Enter Only A-Za-z0-9-,.
But when I removed special chars in one of the text fields and submitting the values again both error messages are displaying instead of only one error message
You are showing the messages but you are not hiding them anywhere. Try this:
if(!summary.match(letters)) {
document.getElementById('errorsum').innerHTML="In Summary Please Enter Only A-Za-z0-9-,_.";
document.getElementById("divname").style.display='block';
document.getElementById("imgsum").style.display='block';
j++;
} else {
document.getElementById('errorsum').innerHTML="";
document.getElementById("divname").style.display='none';
document.getElementById("imgsum").style.display='none';
}
And the same things for description. You could also make it a function so you don't have to write it twice.
Try This Code you should use else part to hide you message
function validateText() {
alert("Hi");
var summary = document.getElementById("summaryOfAlert").value;
var description = document.getElementById("textarea3").value;
var letters = /^[A-Za-z0-9._\-,\s]+$/;
var j;
j = true;
if(summary!="") {
if(!summary.match(letters)) {
document.getElementById('errorsum').innerHTML="In Summary Please Enter Only A-Za-z0-9-,_.";
document.getElementById("divname").style.display='block';
document.getElementById("imgsum").style.display='block';
j=false;
} else{j=true; document.getElementById("divname").style.display='none'; document.getElementById("imgsum").style.display='none';}
}
if(description!="") {
if(!description.match(letters)) {
document.getElementById('errordesc').innerHTML="In Description Please Enter Only A-Za-z0-9-,_.";
document.getElementById("divtype").style.display='block';
document.getElementById("imgdesc").style.display='block';
j=false;
else{ j =true; document.getElementById("divtype").style.display='none'; document.getElementById("imgdesc").style.display='none';}
}
}
return j;
}
</script>

Validation not working on Javascript

I have worked out how to get the alert box up but it seems to skip my other validation which is checking the other feilds, ect, any ideas as too why it is skiiping it? it would really help!
I am fairly new to Javascript and HTML so could you explain it, thank you
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
window.validateForm=function() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
//result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value == "") {
msg += "You must enter the exam Number \n";
document.ExamEntry.subject.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value.length != 4) {
msg += "You must enter at least Four Numbers in the Exam Number \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var Number = document.ExamEntry.Exam_Number.value
if (isNaN(document.ExamEntry.Exam_Number.value)) {
msg += "You must enter at least four numeric characters in the Exam Number feild \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var checked = null;
var inputs = document.getElementsByName('Exam_Type');
for (var i = 0; i < inputs.length; i++) {
if (!checked) {
checked = inputs[i];
}
}
if (checked == null) {
msg += "Anything for now /n";
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} {
alert(msg)
return false;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="Exam_Number">Exam Number</td>
<td><input type="text" name="Exam_Number"<font size="1">(Maximum characters: 4)</font> </td>
</tr>
<tr>
<table><form action="">
<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
and here is a jsfiddle
Change:
var inputs = document.getElementsByName('Exam_Type');
to
var inputs = document.getElementsByName('examtype');
It seems you picked the wrong name for the radio elements.
Your for loop was checking the radio buttons incorrectly.
Code:
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
}
}
Please find the working fiddle here http://jsfiddle.net/sDLV4/2/
I changed code here please check...
Please find the working fiddle here
http ://jsfiddle.net/sDLV4/3/
Using HTML5 constraint validation, much of your code can be dropped, see my revision below. In addition to the wrong radio button group name pointed out by Juergen Riemer, your code has the following issues:
Better use the HTML5 DOCTYPE declaration, see below
Instead of <script language="javascript" type="text/javascript"> just use <script>. The script element does not have a language attribute, and the type attribute has the value "text/javascript" by default.
Do not define your validation function on the window object, but rather as global function (as below), or preferably as a member of a namespace object.
Instead of setting the form's name attribute to "ExamEntry", rather set its id attribute and reference the form of a variable like var examForm = document.forms["ExamEntry"];
Your HTML code is not well-formed, because in your form's table, on line 79, you start another table element with another form element, both of which do not have an end tag.
Also, it's preferable to us CSS for the form layout, instead of a table.
In my revision below I'm using a Pure CSS stylesheet for styling forms, and corresponding class values in certain elements.
For more about constraint validation in general and the HTML5 constraint validation features, see this tutorial.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<title>Exam entry</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/combo?pure/0.3.0/base-min.css&pure/0.3.0/forms-min.css" />
<script>
function validateForm() {
var result = true;
var msg = "";
var checked = null;
var examForm = document.forms['ExamEntry'];
var inputs = examForm.examtype;
for (var i = 0; i < inputs.length; i++) {
if (!checked) {
checked = inputs[i];
}
}
if (!checked) {
msg += "Anything for now /n";
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} else {
alert(msg)
return false;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form id="ExamEntry" class="pure-form pure-form-aligned" method="post" action="success.html">
<div class="pure-control-group">
<label for="exNo">Exam Number:</label>
<input id="exNo" name="Exam_Number" required="required" pattern="\d{4}" title="You must enter a 4-digit exam number" />
</div>
<div class="pure-control-group">
<label>Exam type:</label>
<label class="pure-radio"><input type="radio" name="examtype" value="GCSE" /> GCSE</label>
<label class="pure-radio"><input type="radio" name="examtype" value="A2" /> A2</label>
<label class="pure-radio"><input type="radio" name="examtype" value="AS" /> AS</label>
</div>
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" onclick="return validateForm();">Submit</button>
<button type="reset" class="pure-button">Reset</button>
</div>
</form>
</body>
</html>

Simple input validation and adding values to table

I need to add product info from inputs to table by using jQuery library. I am trying for quite some time now, but I don't get anywhere. First I need to enter data to inputs, select appropriate radio button and than validate input fields. If there are no errors, product info should be added to table. I tried with the following code: jsFiddle
Nothing works as intended tho. What am I doing wrong?
JS code:
$(document).ready(function () {
//Global variables
var productName = "";
var price = 0;
var onStack = "N/A";
$("body > form").submit(function () {
//Check if any of requested inputs is empty
if ($("#name").val().length == 0) {
//Missing name alert
$("#errors").val('Missing product name');
break;
} else if ($("#price").val() == 0) {
//Missing price alert
$("#errors").val('Missing price');
break;
}
//Get values from text inputs
productName = $("#name").val();
price = $("#price").val();
//Check radio buttons and assign values
if ($('input[value = "true"]'.is(':checked')) {
onStack = "Product available";
} else if ('input[value = "false"]'.is(':checked') {
onStack = "Not available";
}
//Add values to table
$("table tr:last").after("<tr><td>$productName</td><td>$price</td><td>$onStack</td></tr>");
});
});
HTML code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="index.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<body>
<form method="" action="">
<input type="text" id="name" placeholder="Product name" />
<br />
<input type="text" id="price" placeholder="Price" />
<br/>
<input type="radio" name="stack" value="true">Product available
<br />
<input type="radio" name="stack" value="false">Product not available
<br />
<input type="submit" value="Submit">
</form>
<div id="errors"></div>
<br />
<table border="1">
<tr>
<th>Product name</th>
<th>Price</th>
<th>Stack</th>
</tr>
</table>
<div id="sumOnStack">Sum of available products</div>
<div id="SumNotOnStack">Sum of unavailable products</div>
<input type="button" id="resetForm" value="Reset form" />
<br />
</body>
</html>
$(document).ready(function () {
//Global variables
var productName = "";
var price = 0;
var onStack = "N/A";
$("body > form").submit(function ( e) {
//Check if any of requested inputs is empty
$("#errors").html('');
if ($("#name").val().length == 0) {
//Missing name alert
$("#errors").html('Missing product name');
return false;
} else if ($("#price").val() == 0) {
//Missing price alert
$("#errors").html('Missing price');
return false;
} else if($('input[name="stack"]:checked').length == 0) {
$("#errors").html('Missing product availibility');
return false;
}
//Get values from text inputs
productName = $("#name").val();
price = $("#price").val();
var stack = $('input[name="stack"]:checked');
console.log( $(stack).val() );
//Check radio buttons and assign values
if ($(stack).val() == 'true') {
onStack = "Product available";
} else {
onStack = "Not available";
}
//Add values to table
$("table tr:last").after("<tr><td>"+productName+"</td><td>"+ price +"</td><td>"+ onStack +"</td></tr>");
return false;
});
});
Please try this. Hope above code will help u.

Categories