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.
Related
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.
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 have two inputs tags. one is quantity and the other is rate.
How can I show the result of the multiplication of those directly into a different input tag straight after the user stop typing?
I'm new to development and I'm finding my way. I'd like to have an input on where to start to sort this out.
Thank you
Maybe this helps a little bit.... (Dirty... i know)
<input id="in1">
<input id="in2">
<input id="in3">
<script>
var val1=0;
var val2=0;
var val3=0;
$(document).ready(function(){
$('#in1').keyup(function(){
val1=$(this).val();
val2=$('#in2').val();
val3=parseInt(val1)*parseInt(val2);
$('#in3').val(val3);
});
$('#in2').keyup(function(){
val2=$(this).val();
val1=$('#in1').val();
val3=parseInt(val1)*parseInt(val2);
$('#in3').val(val3);
});
});
</script>
NOT TESTED
I was wondering if there is a way to copy and paste some part of the text from a third party web page. My boss asked me to enter a group of text (50, 100, 200) one-by-one into this website: http://fbatoolkit.com/chart_details?category=T2ZmaWNlIFByb2R1Y3Rz&rank=500 and copy/paste the information "3 (30 days avg)" into another file. The "rank=500" part is the query string in the url. And I also know where the info, in the html source code, is. It is here:
<div style="margin: 20px">
Estimate sales per day for the rank
<input type="text" name="rank" value="500" />
in this category.
<input type="submit" value="Estimate" />
<table width="200">
<tr>
<td>
3 (30 Days Avg)
</d>
</tr>
<tr>
<td>
More than 2 (Last Day)
</td>
</tr>
</table>
</div>
</form>
I was wondering if there is a way to recursively access the website and copy/paste that part of text into another file. I know it is probably not the smartest way to do things but please help, the almighty stack overflow! I really appreciate that.
So I don't write python but I'll give it a shot. These types of tasks are usually very easy to accomplish with Python. So, I'll give you the general language constructs that I would use complete with links to accomplish this.
General Steps
Set up array of categories
Set up array of ranks to use
For loop through each category and then nested loop through each rank
Within this inner loop, query the web page like this: see This Answer for more options to opening and reading URLS
page = urllib.request.urlopen("URL HERE").read()
Then use RegEx to find the text you're interested in, by doing something like this (Note - the below RegEx was created assuming "(30 Days Avg)" was a static string, which it seemed like from page you supplied. You can re-append this text to the end of the grouped item if you'd like):
match = re.search("(\w+) (30 Days Avg)$", string)
extractedText = match.groups(0)
Append text to file of your choice per This Answer
Close out your loops
Sorry this wasn't more cut-and-paste code. Also the SO text editing syntax doesn't seem to handle code inside lists very well. "extractedText... " should be on its own line.
I need help figuring out how to make this work if anyone can give me some insight as soon as possible even a little help would be greatly appreciated!!!!
<body>
<form name="kdr">
Kills: <input type="number" id="kill" name="kill"></input>
<br>
Deaths: <input type="number" id="death" name="death"> </input>
<br>
<button onclick="kd()"> Calculate</button>
</form>
<script>
function kd()
{
var k = document.getElementById("kill").value;
var d = document.getElementByID("death").value;
var r = k/d
alert("Your kill/death ratio is: " + r)
}
</script>
</body>
I cant seem to get the variables to pull the information from the input field, at least I think that is the issue. Again any insight would be great.
You have ID in your d assignment when it should be Id like in your k assignment.
http://jsfiddle.net/Xaleph/k3Hv9/
Looks like Sam beat me to it. ID should be id and I added semicolons to the end just for good measure.
Also - consider not using inline javascript events. Instead, put your code in a supporting file and handling events similar to the following will make your code a little easier to manage (from w3schools - can't add another link, not enough reputation...).
object.onclick=function(){SomeJavaScriptCode};
Or if you're feeling adventurous, use jquery or another javascript library to handle your events:
$('#buttonId').click(function(){
alert("Your kill/death ratio is: " + ($('#kill').val()/$('#death').val()));
}