I’m learning basic JavaScript. My issue today feels like a simple one, but I’m having a hard time getting a working result.
I’m trying to create a function that subtracts two times (00:00) that the user inputs themselves.
The idea is:
The user inputs their ‘end time’.
The user then inputs how much time they need to subtract.
Lastly, the function runs and returns their ‘start time’, displayed in the HTML.
This is the HTML I’m using
<h1>SUBTRACT TIME</h1>
<div class="timeCalculator">
<input type="time" id="endTime" placeholder="end time">
<input type="time" id="elapsedTime" placeholder="minus...">
<button onclick="calculateTime()" type="button" id="button">Go!</button>
<div id="result-startTime"></div>
</div>
And this is the Javascript
function calculateTime() {
let var1 = document.getElementById("endTime").value;
let var2 = document.getElementById("elapsedTime").value;
let answer = var1 - var2;
console.log(answer);
}
I’ve tried various routes to make this work, but I’ve come up shorthanded every time.
Related
I have a loop of html forms <input type="number">, which are basically simple algebra calculations for certain people to fill in. I set the correct answer by limiting both the max and min accepted number to the same number. However, in this way, if the participant gives a wrong answer, the reject message would be something like this: "values must be greater than or equal to ...". It is technically correct but I would like it to only say "incorrect answer, please try again".
Is there any way to do this?
Tried to use something like alert =, but it doesn't meet my requirements.
There's ${parameters.numbers} and ${parameters.answers} in the code because I am using lab.js for the looping. They just mean every time the number in the equation and the answer would change. For example, for the first loop ${parameters.numbers} is 200, and the corresponding answer ${parameters.answers} is 194. lab.js would take care of converting these two parameters to actual numbers for each loop of the form.
<form>
<label for="algebra">${parameters.numbers} - 6 = ?</label><br>
<input name="algebra" type="number" id="algebra" required="" max="${parameters.answers}" min="${parameters.answers}"><br>
<button type="submit">OK</button>
</form>
I try to avoid a dramatic alert dialogue for this, just a non-intrusive message like the default style would be good. If you want to recreate the default "values must be greater than or equal to ..." message, just replace the parameters like this would be good:
<form>
<label for="algebra">200 - 6 = ?</label><br>
<input name="algebra" type="number" id="algebra" required="" max="194" min="194"><br>
<button type="submit">OK</button>
</form>
I agree with #ElroyJetson that putting the answer inside the tag is not a good idea, but I focused this answer on the way you can set and unset the error message.
I used jQuery, but this can also be done with plain javascript.
The idea is to group the input tag with a span tag (here inside the div with class input-field).
When the value changes or when the form is submitted (in this case when the value changes), you remove any previous error message from the span tag, and then perform the validation. If there is an error you set it in the span tag.
In this way the error message will show below the input element.
To try it fill in an answer and click outside of the input box.
$(document).ready(function(){
$(".input-field").change(function(){
let $inputField = $(this);
let $input = $inputField.find("input");
let $errorMsg = $inputField.find("span.err-msg");
let max = Number($input.data("max"));
let min = Number($input.data("min"));
$errorMsg.text("");
let v = Number($input.val());
if(v < min || v > max){
$errorMsg.text("Invalid answer");
}
});
});
.err-msg{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="input-field">
<label for="algebra">200 - 6 = ?</label><br>
<input name="algebra" type="number" id="algebra" required="" data-max="194" data-min="194"><br>
<span class="err-msg"></span>
</div>
</form>
Don't set the correct answer with min & max. Instead, just call a javascript function by giving your button tag an onClick to evaluate if the user's answer is correct.
<button onclick="evaluateAnswer('.algebra');" class="submitBtn" >OK</button>
Then your javascript should look something like this:
function evaluateAnswer(cssClass){
var usersAnswer = $(cssClass).val();
var actualCorrectAnswer = 100;
if(usersAnswer == actualCorrectAnswer){
//Do something to proceed
}else{
alert('Sorry, your answer is incorrect');
}
}
Also, I just noticed that you did not want to alert as-in a javascript alert. What you could do is style your message and give it a css class that has the property display:none. Then when you want to show the message when user enters the wrong answer, you can use javascript to remove the class, and also use javascript to add the class back when user enters correct answer.
Edit
You should maybe store your correct answers in a database, evaluate it's correctness serverside, and use Ajax to display the message to prevent users from being able to right-click -> view source and look at the answers in your client-side code
My current solution is like this. There is invisible html elements which stores the correct answer, and the js script validates if the input is correct. Again, the ${} parts represents variables that change in each loop.
html part
<main class="content-horizontal-center content-vertical-center">
<form name="mathEvaluation">
<label for="algebra">${parameters.numbers} - 6 = ?</label><br>
<input name="answer" type="number" id="answer" required="" size="3"><br>
<button type="submit">OK</button>
<input type="hidden" id="hidenAnswer" value=${parameters.answers} />
</form>
</main>
js part
this.options.validator = function(data) {
if(mathEvaluation.answer.value == mathEvaluation.hidenAnswer.value){
return true
} else {
alert("Please enter the correct number.")
}
}
I'm currently working my way through a beginner's JavaScript course on Treehouse and keep getting stuck on functions. In effort to understand better, I tried creating a calculator which converts human years to dog years. Here is my code so far:
HTML:
<div id="calculator">
<form>
<label>What is your current age in human years? <br>
<input type="text" id="humanYears"></label> <br>
<button type="text" id="calculate">Calculate</button>
</form>
</div>
JS:
function calculate() {
var humanYears = document.getElementById("humanYears").value;
var dogYears = (humanYears * 7);
document.write(dogYears);
}
document.getElementById("calculate").onclick = function(){calculate(); };
The page flickers and I keep seeing the form, no result.
I know this code is incorrect but I don't understand why. I also know I can just copy other people's code from Github and have a functioning calculator but that kind of defeats the purpose of learning. I would rather know why my code doesn't work and what I can do to fix it. (I double, triple checked that the HTML and JS files were properly linked, which they are.)
Any JS wizards out there care to chime in?
Edit: When I enter an age into the form, it merely reloads, rather than displaying the age in dog years (which is the desired outcome).
Your code works, although as you've indicated it's not great.
function calculate() {
var humanYears = document.getElementById("humanYears").value;
var dogYears = (humanYears * 7);
document.write(dogYears);
}
document.getElementById("calculate").onclick = function(){calculate(); };
<div id="calculator">
<form>
<label>What is your current age in human years? <br>
<input type="text" id="humanYears"></label> <br>
<button type="text" id="calculate">Calculate</button>
</form>
</div>
Some notes for improvement:
Avoid document.write
Forms should have submit buttons (either <input type="submit" value="Calculate"> or <button type="submit">Calculate</button>
The parentheses around your arithmetic are superfluous: var dogYear = humanYears * 7; is sufficient
Not everything needs an id attribute, although that makes DOM queries easy and quick
You should handle the form's submit event as opposed to the button's click event as you'll want to handle if, say, I submit the form by pressing Enter on my keyboard
You don't need the extra function around calculate, document.getElementById('calculate').onclick = calculate; would suffice
With those notes in mind, here's how I'd improve your calculator:
var form = document.getElementById('calculator');
function calculate() {
var years = form['humanYears'].value,
dogYears = years * 7;
document.getElementById('answer').innerText = dogYears;
}
form.addEventListener('submit', calculate, false);
<form id="calculator">
<p>
<label>
What is your current age in human years?<br>
<input type="text" name="humanYears">
</label>
</p>
<p>
<button type="submit">Calculate</button>
</p>
<p>
Answer: <span id="answer"></span>
</p>
</form>
Things I've changed:
I'm using <p> tags to control whitespace instead of <br> which will further let me customize presentation with CSS if I choose to. You cannot style <br> elements.
I'm modifying a portion of the DOM, not the entire DOM
I've bound my event handler with addEventListener which is way less obtrusive
I'm accessing form elements through the natural structure the DOM provides instead of running a full DOM query for each element
I've reduced some code
Here your working code with as little changes as possible:
<div id="calculator">
<form>
<label>What is your current age in human years? <br>
<input type="text" id="humanYears"></label> <br>
<button type="text" id="calculate">Calculate</button>
</form>
</div>
<script>
function calculate() {
var humanYears = document.getElementById("humanYears").value;
var dogYears = (humanYears * 7);
document.write(dogYears);
}
document.getElementById("calculate").onclick = function(){calculate(); return false; };
</script>
Assuming you put everything in one file the script tags are missing. If not then you still need a script tag to load the JS file.
Your function needed a "return false;". If you omit that, the page will reload after writing your output and won't see the output. That happens because the default behaviour of a button in a form is to reload the page. By returning "false" you suppress that.
The main problem is that document.write doesn't do what you imagine it does:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
See the documentation for document.write: https://developer.mozilla.org/en-US/docs/Web/API/Document/write
A better way to this is to have an empty element on the page, which you then change the contents of:
function calculate() {
var humanYears = document.getElementById("humanYears").value;
var dogYears = humanYears * 7;
document.getElementById('output').innerText = dogYears;
}
document.getElementById("calculate").onclick = calculate;
<div id="calculator">
<form>
<label>What is your current age in human years? <br>
<input type="text" id="humanYears">
</label>
<br>
<button type="button" id="calculate">Calculate</button>
<div id="output"></div>
</form>
</div>
I've also made some small improvements to your script:
Changed the indentation of your HTML to be more readable
Changed your button to have type="button" - otherwise your form will submit and the page will reload when you click the button. In this case, you actually don't even need a form element, but it's not hurting anything. Alternatively, you could add return false to your calculate function - this would tell the browser not to submit the form and thus not reload the page
Changed how you're adding the onclick handler - there's no need to wrap the calculate function in another function. In javascript, functions can actually be passed around like a variable. This is why I set the value of onclick to just be calculate - notice however that I left out the (). You want the onclick to be a reference to the function, otherwise the calculate function would be executed immediately, and the onclick would be set to the return value of the function - in this case, that would be undefined.
How do you pass a value or an array from one page to another in html using javascript. I'm not allowed to use local storage or sessions only pass the variable from page to page. I'm sending values from a radio button. I intend to store the results in array as i am keeping track of the users answer to display the result at the end. How do i send an array to quiz_5.html? I intend to keep passing the array instead of using a cookie or local storage as i am not permitted to.
Below is My code:
<div>
<form>
<input type="radio" name="radio" value="correct" class="firstRow"> NASA.Gov
<input type="radio" name="radio" value="incorrect" class="secondRow"> Data.Gov <br>
<input type="radio" name="radio" value="incorrect" class="firstRow"> Facebook
<input type="radio" name="radio" value="incorrect" class="secondRow"> XYZ.net <br>
<input type="button" value="Submit & Next Question" onclick="getAnswer4(this.form)" class="firstRow">
<input type="button" value="Cancel & Clear Selection" onclick="clearOptions(this.form)" class="secondRow">
</form>
</div>
Javascript code:
function getAnswer4(form) {
var a[];
var value;
var checked = form.querySelector("input[type=radio]:checked");
if(!checked) {
alert('Please select an answer');
return;
}
else{
value = checked.value;
}
a.push(value);
location.href = "quiz_5.html";
}
You should just have one HTML button for the entire form. First, let's fix that form tag:
<form name='form' id='form' method='get' action='quiz_5.php'>
Now let's add a submit button to the bottom of the form:
<input type='submit' name='sub' id='sub' value='Submit' />
On quiz_5.html
var pre = onload;
onload = function(){
if(pre)pre();
var resultObject = {};
var fs = location.search.replace('?', '').split('&');
for(var i=0,l=fs.length; i<l; i++){
var z = fs[i].split('=');
resultObject[decodeURIComponent(z[0])] = decodeURIComponent(z[1]);
}
/* resultObject now has values based on name attibute
for instance resultObject.radio will hold value of name='radio' where it's checked */
}
Sorry if my comments seemed harsh, but I am all about new coders learning the basics themselves without relying on having the answers provided. Just to show it can be done - I just created three HTML pages. Created a form in the first two - each with your questions (questions 1 and 2 in the first page and question 3 in the second page), and passed the form values to the next one, using nothing more than html.
Then using only JavaScript on the second and third pages, I grabbed the values out of the URL and did stuff with them. On page two, I re-used the values from page 1 (think how that might have been done and why it is useful) so that all three values are passed to page 3 which then used JavaScript only to grab the 3 values, display them on the page (as shown in the code section below) and calculate the total and the percentage of answers that are correct. Note that I answered the questions so that I got question 2 incorrect.
Note that I am not giving the code used, but will give you the URL of the pages so that you can see the outcome of the previous two pages and can then start to think how I achieved this.
numbers1.html
numbers2.html?one=correct&two=incorrect
numbers3.html?one=correct&two=incorrect&three=correct
Question 1: correct
Question 2:incorrect
Question 3:correct
2/3
0.67% correct
Not a traditional answer I know, but it is not ideal for learners simply ask for the answer to be provided, especially when in 10 minutes I was able to put together the three pages that achieved the outcome. If you do not try then you will not learn for yourself.
I am trying to create something in javascript that will allow me to calculate total number of credit hours. I am very new at this and I don't even know where to begin.
Here is what I need to do:
Create a web page that will allow to calculate totals number of credit hours taken by a student in the semester.
A page should include separate input fields to enter a number of one, two, and three credit hour courses, taken by a student.
Then once a result button is clicked, the total number of hours should be displayed. Use function to calculate total number of hours.
Here is what I have and I have no idea if it is even right so don't get mad:
<script>
function doSmth(){
var value = document.getElementById("credithour").value;
var doubled = value * 2;
document.getElementById("output").innerHTML = doubled;
}
</script>
<body>
1 credit hour: <input id="credit"><br />
2 credit hour: <input id="credit2"><br />
3 credit hour: <input id="credit3">
<button onclick="doSmth()">calculate</button>
<div id="output"></div>
You are pretty close but it looks like there are a few things you aren't quite grasping completely.
In your HTML you have 3 input boxes declared which is perfect and
you give them the id "credit", "credit2" and "credit3". However you
are then only grabbing one of them in your JavaScript function and
even then you are using the incorrect name "credithour"!
Then in your function you are doubling the value you have retrieved
from the input box when you are meant to be summing them all together!
Finally you are displaying it and your code for that actually looks
ok. There are some security issues around setting HTML using
innerHTML but if this is just a page for yourself and you aren't
allowing users to set strings using it you should be fine. Make a note to look into it though.
Although Stack Overflow isn't a code factory I quite like your question, it is clear and shows the effort you have done so far, so I've went to the extra effort of giving you a worked example you can hopefully use and learn from.
It isn't the most perfect JavaScript in the world but it will give you enough to get started.
I also highly recommend jsFiddle for this sort of thing, it allows you to quickly write, test and share JavaScript code with the rest of the world. Click the link below and you'll be able to edit my code, hit RUN and see how your changes affect it. You can also then SAVE your results into your own copy, just hit SAVE and copy the link!
Here is the jsFiddle that does what you are looking for: https://jsfiddle.net/jcos29eb/2/
And here is the revised code:
HTML:
<body>
1 credit hour:
<input type="number" id="credit1">
<br /> 2 credit hour:
<input type="number" id="credit2">
<br /> 3 credit hour:
<input type="number" id="credit3">
<br /> Total:
<input id="output">
<br />
<button onclick="doCalc()">Calculate</button>
</body>
JavaScript:
function doCalc()
{
var value1 = document.getElementById("credit1").value;
var value2 = document.getElementById("credit2").value*2;
var value3 = document.getElementById("credit3").value*3;
var total = Number(value1) + Number(value2) + Number(value3);
document.getElementById("output").value = total;
}
My final recommendation is to spend some time going through the W3Schools JavaScript Tutorial it is really clear, easy to understand and covers lots of JS basics and some more complicated things.
This is my first time using jquery and while this is a fairly simple task I'm stuck already.
I've got a input box with the time of day in it. I would like to create a button to grab the time and send it to a variable (setTime) so I can use the time elsewhere in the script.
However I'm having trouble the variable to pass, I've added an alert window but all I get is either a blank alert or an "undefined" alert.
The first line Start Time.... works fine its the setTime stuff that's broken.
Page header:
setTime = $('#setTime').text();
$('#formTime').timeEntry({show24Hours: true});
Page body:
<p>Start Time <input type="text" size="2" id="formTime" class="spinners" value="" /> </p>
<input type="button" value="Set Time" onclick="$('#setTime').val('#formTime');" />
<input type="button" value="Show Date" onclick="alert(setTime);" />
Thanks
You have to make a few changes to your code.
Update your Html by adding some ids for example.
<p>
Start Time <input type="text" size="2" id="formTime" class="spinners" value="" />
</p>
<input id="setTime" type="button" value="Set Time" />
<input id="showTime" type="button" value="Show Date" />
Personally I don't like assigning script to events within the html controls as they become hard to maintain and add clutter to the page.
You can write script at the bottom of the html page within a script tag or better yet, use an external js file. External js files will also keep your Html clean and your scripts unobtrusive.
var setTime = 0;
var $fromTime = $("#formTime")
$("#setTime").off("click").on("click", function(){
setTime = $fromTime.val();
});
$("#showTime").off("click").on("click", function(){
alert(setTime);
});
See working DEMO
Using jQuery can be confusing at times but the on-line documentation is fantastic.
#setTime means "The element with the id 'setTime'" - you have no element with that id, and the control you are trying to get the value of has no id at all.
timeEntry is not a jQuery method, so will error when you try to call it. If you are using a plugin that you think should add that method then you should say so.
.val('#formTime') will set the value of a form control to the string #formTime. If you want to get the value, don't pass that method an argument … and do assign the return value of the method call to something.
You should probably work through an introduction to programming and JavaScript.