I'm creating a nutrition JavaScript calculator where the user enters a daily calorie intake and selects their percentage of carbohydrate, protein, and fat. The result is the percentage of calories and grams from each nutrient. I've got it working but...
As a math check/validation, I want to include some code that will add up the selected carbohydrate, protein, and fat percentages and ensure they equal exactly 1 (or 100%). If this is not true, then I want a little alert/error message to pop up so they know to go back and fix this before the "Calculate" button will work.
Here is the relevant code for what I'm trying to ensure adds up to 1
Thanks in advance for any advice you can provide.
I'm a relative novice with JS, so I'm not even really sure of the exact code I need to use in this case.
<script type="text/javascript">
function calc (form) {
var C, P, F
P=form.Protein.options[form.Protein.selectedIndex].value
F=form.Fat.options[form.Fat.selectedIndex].value
C=form.Carbohydrate.options[form.Carbohydrate.selectedIndex].value
}
</script>
function calc(form) {
const errorEl = document.getElementById('error');
// Clear the error before calculating the new value.
errorEl.innerText = 'Your error message';
const protein = form.Protein.options[form.Protein.selectedIndex].value;
const fat = form.Fat.options[form.Fat.selectedIndex].value;
const carbohydrate = form.Carbohydrate.options[form.Carbohydrate.selectedIndex].value;
if (Number.isNaN(prtein) || Number.isNaN(fat) || Number.isNaN(carbohydrate)) {
document.getElementById('error').innerText = 'Your error message';
return;
}
const sum = parseFloat(protein) + parseFloat(fat) + parseFloat(carbohydrate);
if (sum > 1) {
document.getElementById('error').innerText = 'Your error message';
}
}
And you also need an element with the error id in your form that will show the error message. For example <p id="error"></p>
Related
I have the following problem: after the input in a field I check if the value of the field is ok.
var oCheckGrossTons = oGrossTons.getValue();
var Msg = this.getResourceBundle().getText("validation.grossTons");
if (oCheckGrossTons < 500)
{var oMessage = new Message({
message: Msg,
type: MessageType.Error
});
sap.ui.getCore().getMessageManager().addMessages(oMessage);
So and now I want to color the border of this field in red so the user can see where he made a mistake.
So I tried to solve this with a jQuery. I created a CSS style like:
.rrpGrossTons {
border-color: "red"}
and my jQuery looks like this:
$("...").addClass('.rrpGrossTons');
So my main problem is, how do I get the ID of the field, because I think I have to enter the ID in the ("...") after the $ symbol. And is the Syntax of my jQuery correct?
You might want take a look at the valueState property of the InputBase (see an example)
Even better, you could use Constraints and let UI5 handle the validation for you.
<Input
textAlign="Right"
type="Number"
value="{
path: '/Grosston',
type: 'sap.ui.model.type.Float',
constraints: {
minimum: 0,
maximum: 500
}
}"/>
SAP has build in functionality for what you want to achieve:
// Mark control as not valid:
oGrossTons.setValueState(sap.ui.core.ValueState.Error);
// Reset the error state
oGrossTons.setValueState(sap.ui.core.ValueState.None);
So in your code it would be:
var oCheckGrossTons = oGrossTons.getValue();
if (oCheckGrossTons < 500) {
oGrossTons.setValueState(sap.ui.core.ValueState.Error);
var Msg = this.getResourceBundle().getText("validation.grossTons");
oGrossTons.setValueStateText(Msg);
var oMessage = new Message({message: Msg, type: MessageType.Error});
sap.ui.getCore().getMessageManager().addMessages(oMessage);
} else {
oGrossTons.setValueState(sap.ui.core.ValueState.None);
}
or use constrains as #A.vH mentionned in his answer.
Okay after a hard weekend I have found a solution for my Problem
var oCheckGrossTons = oGrossTons.getValue();
if (oCheckGrossTons < 500) {
this.setInvalidGrossTons(oGrossTons.getId());
} else {
this.removeErrorMsgForId(oGrossTons.getId());
}
and
setInvalidGrossTons: function (id) {
var oMessageProcessor = new sap.ui.core.message.ControlMessageProcessor();
var mainMsg = this.getResourceBundle().getText("validation.grossTons");
var msg = new sap.ui.core.message.Message({
message: mainMsg,
additionalText: "",
description: "",
type: sap.ui.core.MessageType.Error,
target: "/" + id + "/value",
processor: oMessageProcessor
});
this.bus.publish("rrp", "validationError", {
message: msg
});
},
so the only problem I am having now:
When I enter 100 tons i get the error Message :-)
If I enter 200 tons i get the error Message twice
Until I enter more than 500 tons ther are no error Messages anymore.
So how do I remove the double Error Message?
I think the Problem is in my MessageProcessor.constructor
There I am having 2 Entries withc different ID´s . I think I can solve the problem by remove the ID but i dont know how .
enter image description here
I'm trying to create a PDF with a submit button that runs a custom JavaScript. The purpose of the code is to determine the value of one of the form fields and then run a math equation to determine if a warning should be displayed to the user or if they should be allowed to submit.
There are 3 scenarios I want to account for when the user clicks the submit button:
If the "CompletedValue" field is greater than or equal to 1,500,000 and the equation returns a value of less than 40. If this is true, the form should generate error message 1.
If the "CompletedValue" field is less than 1,500,000 and the equation returns a value of less than 25. If this is true, the form should generate error message 2.
Scenario 1 & 2 are false. If this is true, the form should generate an email.
To accomplish this I've written the following code, however, it is not working. When I click the Submit button, nothing happens.
var cV = this.getfield("CompletedValue").value;
var nV = cV - this.getfield("PresentValue").value;
var percentage = ( nV / cV ) * 100;
if (cV >= 1500000 && percentage < 40)
{
var error1= app.alert(errorMessage1,0,0,cTitle);
}
else if (cV < 1500000 && percentage < 25)
{
var error2= app.alert(errorMessage2,0,0,cTitle);
}
else
{
this.mailDoc({bUI: true, cTo: cToAddr, cSubject: cSubLine, cMsg: cBody});
}
Any help on getting this to work would be appreciated.
I resolved this issue simply by changing the case in the first two statements.
The case I used originally was:
var cV = this.getfield("CompletedValue").value;
This was corrected to:
var cV = this.getField("CompletedValue").value;
Note the capital 'F' in the getField.
{!REQUIRESCRIPT("/soap/ajax/33.0/connection.js")}
/*Getting the Running User Details*/
var result =
sforce.connection.query(
"SELECT Advisor__c " +
"FROM User " +
"WHERE Id = '{!$User.Id}'"
);
/*Grab the Records returned by executing the above SOQL Query*/
var userDetails = result.getArray("records")[0];
/*Initializing the Contact record for Update*/
var contactToUpdate = new sforce.SObject("Contact");
contactToUpdate.Id = "{!Contact.Id}";
/*If the Running User is an "Advisor" then set the
Contact With and associated fields*/
if(userDetails.Advisor__c === true){
contactToUpdate.Contact_With__c = "{!$User.Id}";
contactToUpdate.Last_Advisor_Touch__c = new Date();
}
/*If the Running User isn't an "Advisor" then set the
Contact With 2 and associated fields*/
else{
contactToUpdate.Contact_With_2__c = "{!$User.Id}";
contactToUpdate.Last_Non_Advisor_Touch__c = new Date();
}
var result = sforce.connection.update([contactToUpdate]);
if(result[0].success === true){
location.reload();
}
else{
alert(result[0].errors.message);
}
I added a custom check box field to our user profiles titled "Advisor" The code is suppose to distinguish which field to update based on if a user has this box checked or not. If yes update this field, If not update that field. Instead though it's returning a 'Unexpected Token ILLEGAL. Not sure why.
Seems like you have a special hidden character in following line
contactToUpdate.Last_Advisor_Touch__c = new Da te();
in word Date
If you just rewrite it it should work.
Specifically you have the infamous ZERO WIDTH SPACE between Da and te probably comes from this. To eliminate such things you can use this tool or this one
I'm working on a javascript program that is a simple guessing game. It comes up with a random number between 1 and 10 and provides an input field and a button for the user to make their guess. The program tells after each guess whether the user guessed too high or too low, and it keeps up with the number of guess it took the user to get the correct answer which it displays along with a "congratulations" message when they get it right.
I'm having some trouble getting it to work properly. The page displays properly, but when I enter a guess and click my submit button, nothing happens.
Here is my code:
<html>
<head>
<title>Guess My Number</title>
<script type="text/javascript">
var game = {
num : 0,
turns : 1,
reset : function() {
this.turns = 1;
this.newNum();
},
newNum() : function() {
this.num = parseInt(Math.random() * 10) +1;
},
checkNum() : function(guess) {
try {
guess = parseInt(guess);
}
catch(e) {
alert("Enter a guess!");
this.turns++;
return false;
}
if (guess == this.num) {
alert("Correct! It took you " + this.turns + "turns to guess my number.");
return true;
}
else if(guess > this.num) {
alert("Your guess is too high. Try again.");
this.turns++;
return false;
}
else (guess < this.num) {
alert("Your guess is too low. Try again.");
this.turns++;
return false;
}
}
};
function guessNumber() {
var guess = document.getElementById("guess").value;
game.checkGuess(guess);
}
function resetGame() {
game.reset();
}
resetGame();
</script>
</head>
<body>
<h1>Would You Like To Play A Game?</h1>
<h2>Thank you for checking out my game. Good luck!</h2>
<h3>Created by Beth Tanner</h3>
<h2>Directions:</h2>
<p>
The game is very simple. I am thinking of a number between 1
and 10. It is your job to guess that number. If you do not guess
correctly on your first attempt, don't worry, you can keep guessing
until you guess the correct number.
</p>
<p>
Your Guess: <input type="text" id="guess" size="10" />
<br />
<input type="button" value="Sumbit Guess" onclick="guessNumber()" />
<input type="button" value="Reset Game" onclick="resetGame()" />
</p>
</body>
</html>
I've never actually worked with Javascript before so I know this is probably a very basic thing that I'm overlooking. Any ideas as to why this isn't working correctly?
You variable guess is undefined.
Just initialize it with :
var guess = 0;
However be careful there's a possibility that num is initialize to 0. So, the user guessed immediatly without doing nothing.
var num = Math.random() *10 + 1;
BR
You should call your function in first place, one possible thing you can do is:
<input type = "button" value = "Submit Guess" onclick="guessNumber()">
now that your function is called you need to get the value entered by the user into your guess variable, which I don't see in your code, you can do it as:
Your guess:<input type = "text" name = "guess" size = "10" id="guess" /> <br />
and then in your java script initialize the variable guess as:
guess=document.getElementById("guess").value;
This should do the thing!
EDIT:
Also make sure that Math.random() returns an Integer,as others have suggested use Math.ceil() !
Several other answers have pointed out some issues in the test code:
type="submit" but no <form> tags.
Misspelled variable name tunrs instead of turns.
Use of the while loop
No event connections between the buttons and the JavaScript
This is a simple code example, and there are so, SO many ways to tackle it in JavaScript. Here is my method.
When creating a simple game board where the page does not need to be reloaded, I like to create a game object. In JavaScript you can create objects in a variety of ways. But one of the simplest is this:
var game = {};
This creates an empty object with no properties or methods. To create a couple of properties:
var game = {
num: 0,
turns: -1
};
Each of these properties can be referenced globally like var x = game.num;. To create the object with a function:
var game = {
num: 0,
turns: 0,
reset: function() {
this.turns = 0;
//get a random integer between 1 and 10
this.num = parseInt(Math.random() * 10) + 1;
//Note: "this" lets you refer to the current object context. "game" in this case.
//There are a couple of ways to force the value to an Int, I chose parseInt
}
};
Game now has a game.reset() function that will set game.turns back to 0 and get a new game.num. Here is the full javascript code for my example (slightly different than the above examples):
<script type="text/javascript">
//Create an object to hold the game info
var game = {
num : 0,
turns : 0,
reset : function() {
//function to reset
this.turns = 0;
this.newNum();
},
newNum : function() {
//get a random integer between 1 and 10
this.num = parseInt(Math.random() * 10) + 1;
},
checkGuess : function(guess) {
//try to convert the guess into a integer
try {
guess = parseInt(guess);
} catch(e) {
alert("Enter a guess!");
this.turns++;
return false;
}
//perform strict check of equality
if (guess === this.num) {
alert("Correct! It took you " + this.turns + " turn(s) to guess my number");
return true;
} else if (guess > this.num) {
alert("Your guess is too high. Try again.");
this.turns++;
return false;
} else {
alert("Your guess is too low. Try again.");
this.turns++;
return false;
}
}
};
function guessNumber() {
var guess = document.getElementById("guess").value;
game.checkGuess(guess);
}
function resetGame() {
game.reset();
}
resetGame();
</script>
Note: I didn't do a window.onload event here because those are only needed when the code will be interacting with elements on the document, or DOM elements. If you try to execute JS code in the head of the document, it gets executed instantly before the rest of the document gets loaded. This is bad if your JS code is trying to get, set, or manipulate elements in the page because you're still in the head and the body hasn't been loaded yet.
So in the case where your code needs to get access to elements of the page, often a window.onload = someInitFunction(); will be used so that the JS code will be executed after the document has completed it's load.
Below is my HTML code. It is mostly similar to your code except that I change the name attribute to id on the "guess" input to make it easier to access with document.getElementById(). Using name is helpful when you are in a form and will be submitting values to a server. Only fields with the name attribute set get submitted in that case. Often on forms you will have something like <input type="text" id="textfield" name="textfield" />. The id is used in JavaScript for easy of access, and name is used when submitting the form back to the server.
I also added onclick attributes to the buttons, and changed the input type="submit" to input type="button".
<h1>Would You Like To Play A Game?</h2>
<h2>Thank you for checking out my game. Good luck!</h2>
<h3>Created by Beth Tanner</h3>
<h2>Instructions</h2>
<p>
The game is very simple, I am thinking of a non-decimal number between 1 and 10
and it is your job to guess what that number is. If you do not guess my number
correctly on your first attempt, that's ok, you can keep guessing until you are correct.
</p>
<p>
Your guess:<input type="text" id="guess" size = "10" />
<br />
<input type="button" value = "Submit Guess" onclick="guessNumber()" />
<input type="button" value = "Reset Game" onclick="resetGame()" />
</p>
Here is a JSFiddle example that operates, I believe, the way you want it to.
update
As I was saying there are so many ways to do this. Here is an alternate way to give number selections.
A few issues with your code:
Math.random()*10 will return something that looks like 8.523525235, so you'll have a hard time matching that to any guesses. Instead, use Math.ceil(Math.random()*10). This generates a random number and then rounds up to the nearest integer.
In your JavaScript code, you're calling guessNumber() on the last line, which will execute the function as soon as the browser gets to that line. This will mean the function being executed before the user puts in any guesses. Instead you need to attach an event listener to the button, so that when the button is clicked, guessNumber() is called. Something like:
document.getElementById('button').addEventListener('click', guessNumber).
Right now you're not setting the variable guess in any way. You need to grab the value of the text box and assign that to guess. Something like:
guess = document.getElementById('textbox').value
Using a while loop is not appropriate here, since the user is using the textbox and the button to submit guesses each time. There are ways of doing this with a while loop, but let's stick with your current setup.
You want something that resembles this:
HTML:
<p>Your guess:
<input type="text" id="textbox" />
<input type="button" id="button" value="Guess" />
</p>
JS:
var rand = Math.ceil(Math.random()*10);
var turns = 0;
var guess;
document.getElementById('button').addEventListener('click', guess);
function guess() {
guess = document.getElementById('textbox').value;
if (guess == rand) {
alert('Correct! It took you ' + turns + ' turns to guess the number!');
} else if (guess < rand) {
alert('Your guess is too low. Try again.');
turns++;
} else if (guess > rand) {
alert('Your guess is too high. Try again.');
turns++;
} else {
alert('You didn\'t enter a number. Try again.');
}
}
Here's a fiddle. I added some for the reset functionality.
I need to create a conversion chart from degrees Celsius, to degrees Fahrenheit. To do this, I need to use javascript to prompt the user for input for three things: starting temp in Celsius, ending, and the interval at which it will be displayed. Example:
start:100
end:10
interval:10
100 conv
90 conv
80 conv
70 conv
... conv
10 conv
Additionally, this data needs to be displayed in a table. Our instructor has not taught us how to dynamically change or create html or css elements, so I'm a little lost on how I will get the specific amount of cols and rows that ill need, and how I'll get the data in the right position before and after conversion.
Please help!
EDIT so I've been trying, and so far I have something. it looks like:
<script language = "javascript" type="text/javascript">
function prompts()
{
var startingTemp = prompt("Please enter the starting temperature.","Degrees Celsius");
var endingTemp = prompt("Please enter the ending tempurature.","Degrees Celsius");
var intervalTemp = prompt("What interval do you wish to display between the two?","Interval Number");
}
function table()
{
var myTable= "<table><tr><th>Celsius</th>";
myTable+= "<th>Farhenheit</th></tr>";
myTable+= "<tr><td>"+startingTemp"</td>";
myTable+= "<td>212</td></tr>";
myTable+= "</table>";
document.write(myTable);
}
prompts();
table();
</script>
however, the line where I have "+startingTemp" somehow messes it all up and won't print anything. With this included, the table doesn't print anymore and I'm also not being prompted when I reload the page. I'm just trying to get the value of startingTemp displayed there.