Take numbers from input and plug into an equation javascript - javascript

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()));
}

Related

How can I separate a function in a string inputted by the user and plot this function?

I am trying to make a program in JavaScript/HTML where the user inputs a string that is a math function such as cos(x)+3 or x^2-1 and the the JavaScript program parses this input and plots it using p5.js. I am not looking for a solution to the entire problem, but instead a way to start approaching the problem or an external library that might help.
I've done some research to see how I might solve this but I can't find anything except some Python and Objective-C solutions. What is a JS function/framework that I can use to parse this input into a function?
Please have a look at the below snippet. I'm making use of javascript "eval" function where you can literally run arbitary code.
Use of eval should be done judiciously. As you can run literally any arbitary input. Perhaps you can apply stringent input sanitization mechanism etc. This is not a complete solution rather a starting point to build something more complex.
I hope this helps
function doMath(){
let expr = document.forms[0].mathExpr.value
document.getElementById("output").innerText = eval(expr);
}
<html>
<head>
<title>Math program Example</title>
</head>
<body>
<form>
<label>Please enter math expression:</label><input type="text" name="mathExpr" value="" />
<input type="button" name="result" value="Result" onclick="doMath();" />
</form>
<h2>Result: <span id="output"></span></h2>
</body>
</html>

Beginner Javascript credit hour calculator

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.

Using Javascript to display an input (A number) from a user to a div

I have looked at the other questions that are asking similar things to this question however when I attempted to create my own I can't get it to work properly and i dont understand why. It's only very basic before I introduce it into a more complex system I just wanted to try and get the functionality done.
This is my HTML;
<div id="test2">
Please enter a number: <input type="number" id="RValue1">
<button id="test" onclick="R1Value()">Change Value</button>
</div>
<div id="ShowR1"></div>
And this is the JavaScript;
function R1Value() {
var t = document.getElementById("RValue1");
var div = document.getElementById('ShowR1');
div.innerHTML = t.value;
}
I have made this fiddle to save time and so you can have a look at it,
http://jsfiddle.net/2ufnK/52/
I can't see why this doesn't seem to work so if anyone can see why I would really appreciate it. Thanks.
Try it without the button:
Try out this: http://jsfiddle.net/2ufnK/56/
Type in the text, then you can just call the, ".value", method to get its text. Then everything else works the way you've written it.

Convert HTML text area value to jqmath formula

I am new to jqmath; I have contained a textarea field in my HTML:
<textarea cols="30" rows="2" id="mathSrc1"></textarea>
I will set mathematical formula in the text area so that it will be displayed in <div> tag:
<div id="mathTgt1"></div>
This code is available in http://mathscribe.com/author/jqmath.html. But I don't know how to use it. Please help me.
Thank you.
i got solution
<input type="textarea" name="formula" id="test_formula" onkeyup="paste_formula()" />
<span id="formula_print"></span>
script code
function paste_formula() {
var val = document.getElementById("test_formula").value;
val = "$$" + val + "$$";
var di = document.getElementById("formula_print");
di.innerHTML = val;
M.parseMath(di);
}
I like Nathan's question - what exactly are you trying to do? The normal case is to have some math in your static web page, which you just surround with $s and it gets parsed and formatted at load time. If you want to create mathematical expressions dynamically (after load time), see Jqmath - apply after page load. You can also look at the jqmath source to see how http://mathscribe.com/author/jqmath.html does it. All these methods end up calling the same functions to do the actual work (parsing and formatting).

HTML/Javascript search function with AJAX

I've created a webpage where I want users to be able to search for a word/term stored in a CSV file, and if that term is found the full line for that line entry will be returned and displayed to the user (ideally in table format, otherwise a textarea will do).
But I need to do this using AJAX, and I also cant use PHP (unfortunately, otherwise I wouldn't be asking this question).
So far I have a table for the form/input/button, and I've also got the code to read the file, but I'm a bit stuck with bringing both together. I know this should be an easy thing to do, but I've spend a lot of time going through tutorials and online questions but havent been able to find anything similar.
If anyone knows of any tutorials that covers this, or can help out with the code below it would be appreciated.
<table>
<tr><td>Enter Search Term:
<input type="text" name="searchword" />
<input type="button" name="searchbutton" value="Search" onclick="contentDisp();">
</td></tr>
<tr><td><textarea id="contentArea" rows="40" cols="60"></textarea></td></tr>
</table> //currently using text area but ideally this would be displayed in a table
<script type="text/javascript">
function contentDisp()
{
$.ajax({
url : "file.csv",
success : function (data) {
$("#contentArea").html(data); // I THINK SOMETHING NEEDS TO GO IN HERE, WHICH WILL GRAB THE SEARCH TERM ABOVE AND THEN ONLY DISPLAY FILE CONTENTS USING THAT TERM, POSSIBLY 'CONTAIN' */
}
});
}
</script>
It is possible to do this strictly via JavaScript by using some strpos and indexOf functions (indexOf is the starting point, while the other will look for the string delimiter(s) ).
it is also possible to do the task with php if you feel comfortable with it, if you're restricted by domain-origin restriction, take a look at JSONP, which stands for JSON with Padding - which basically means that you'll need to wrap the result in a JavaScript function.
good luck.
User Regular Expressions to find your string and to parse the found line in the CSV data.
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
HTML
<input type="text" id="text" />
<input type="submit" id="btnsubmit" />
Script
$(function(){
$('#btnsubmit').on('click', function(){
var csv = $.ajax('text.csv');
csv.done(function(data){
var str = data.split(',');
var value = $('#text').val();
$.each(str, function(index, item){
if(item.match(value)){
console.log(item) //Output
};
})
})
})
});
CSV
Presidency ,President ,Wikipedia Entry,Took office ,Left office ,Party ,Portrait,Thumbnail,Home State
Why would you use strpos and indexOf when javascript already has built-in functions for matching strings?
http://jsfiddle.net/AWZg8/

Categories

Resources