textbox calculator with parsing function to arithmetic function - javascript

What I'm trying to do is have 2 text boxes that connect to one button. When the button is clicked, it calls a function to parse the 2 text box entries and then perform an addition (2 seperate functions). Can anybody point out what I'm missing on this? I keep getting num1 as undefined when I call it in the console.
<!DOCTYPE html>
<html>
<head>
<title>.</title>
</head>
<body>
Number1: <input type='text' id='num1'><br>
Number2: <input type='text' id='num2'><br>
<br>
<button onclick='add()'>Add</button>
<div id='toUser'></div>
<script>
var user = document.getElementById('toUser');
var n1 = document.getElementById('num1').value;
var n2 = document.getElementById('num2').value;
function parsing()
{
var num1mod = parseFloat($('n1')).value;
var num2mod = parseFloat($('n2')).value;
if (isNaN(num1mod || num2mod))
{
user.innerHTML = ('Please enter a valid number');
}
else
{
add();
}
}
function add()
{
parsing();
return num1mod + num2mod;
user.innerHTML = (return)
}
</script>
</body>
</html>

Try this,
function parsing()
{
var user = document.getElementById('toUser');
var n1 = document.getElementById('num1').value;
var n2 = document.getElementById('num2').value;
var num1mod = parseFloat(n1);
var num2mod = parseFloat(n2);
if (!isNaN(n1) || !isNaN(n2))
{
user.innerHTML = 'Please enter a valid number';
}else{
var total = num1mod + num2mod;
user.innerHTML = total;
}
return false;
}

There are a few problems with this code:
$('num1') appears to be jQuery or some other library. From the tags though it doesn't look like you are using jQuery.
If you are using jQuery, $('num1') is an invalid selector. It should be $('#num1')
If you are using jQuery, it should be .val() rather than .value and it should be inside the preceding parenthesis ($('#num1').val()), not outside.
Native JavaScript:
var num1mod = parseFloat(n1, 10);
var num2mod = parseFloat(n2, 10);
jQuery:
var num1mod = parseFloat($('#num1').val(), 10);
var num2mod = parseFloat($('#num2').val(), 10);

Related

How to make a value show up?

Im trying to make a a simple form to calculate my client's services. I want to make a function that adds up the services' values and show them right away without clicking in the button. I have no idea where I'm wrong.
<p>In total: <span id="number"></span></p>
<script>
var kilometry = document.getElementById("kilom").value;
var DoSto = document.getElementById("myRange1").value;
var OdSto = document.getElementById("myRange2").value;
var z = (+kilometry*2.5) + (+DoSto*20) + (+OdSto*80);
var x = document.getElementById("number");
x.innerHTML = z.value;
z.oninput = function() {
x.innerHTML = this.value;
}
</script>
Can you explain why it doesnt work? smh
Your script is running immediately and once only. You need to introduce an event that occurs each time you change the value of an input.
<p>In total: <span id="number"></span></p>
<input id="kilom" onchange=calculateTotal()>
<input id="myRange1" onchange=calculateTotal()>
<input id="myRange2" onchange=calculateTotal()>
<script>
function calculateTotal() {
var kilometry = document.getElementById("kilom").value;
var DoSto = document.getElementById("myRange1").value;
var OdSto = document.getElementById("myRange2").value;
var z = (+kilometry*2.5) + (+DoSto*20) + (+OdSto*80);
var x = document.getElementById("number");
x.innerHTML = z;
}
</script>
function calculateTotal() {
var kilometry = document.getElementById("kilom").value;
var DoSto = document.getElementById("myRange1").value;
var OdSto = document.getElementById("myRange2").value;
var z = (+kilometry*2.5) + (+DoSto*20) + (+OdSto*80);
var x = document.getElementById("number");
x.innerHTML = z;
}
<p>In total: <span id="number"></span></p>
<input id="kilom" onchange=calculateTotal()>
<input id="myRange1" onchange=calculateTotal()>
<input id="myRange2" onchange=calculateTotal()>
The variable z is not an input element. It is a number. So you cannot access .value or .oninput on that variable.
So in that regard. This..
x.innerHTML = z.value;
Should be..
x.innerHTML = z;
And I guess you want the value in the x tag to update in realtime? You need to add event listeners to all the input elements you use to calculate the z variable.
So that means the following code..
z.oninput = function() {
x.innerHTML = this.value;
}
can be rewritten as..
function calculateZ() {
var z = (+kilometry*2.5) + (+DoSto*20) + (+OdSto*80);
x.textContent = z; // x.innerHTML = z; works as well, but is less safe.
}
// Triggers when changing the value in the kilom, myRange1 and myRange2 input tags
document.getElementById("kilom").addEventListener('change', calculateZ);
document.getElementById("myRange1").addEventListener('change', calculateZ);
document.getElementById("myRange2").addEventListener('change', calculateZ);

Add user input to array // Javascript

This is the code I have so far. When the user enters a word into the input box, I want that word to be stored in an array via the Add Word button. Once a number of words have been entered, the user clicks the Process Word button and I want all the words in the array to appear. How would I do this? Also could someone also explain why when nothing is entered into the input box "field is empty" does not appear?
function begin() {
var word = "List of words";
var i = returnword.length
if (userinput.length === 0) {
word = "Field is empty"
}
document.getElementById('message2').innerHTML = word
while (i--) {
document.getElementById('message').innerHTML = returnword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
var arrword = [];
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
Addword()
Your function contains an array arrword. If you keep it inside your function it will be reset every time you call the function. You need to keep your array of words outside the function
Empty input
The empty input message should be shown when you click on the Add word button. Check the input and display a message if needed
Display word
You can simply use join() to display you array
var arrayOfWord = [];
var inputElement = document.getElementById('userinput');
var errorElement = document.getElementById('error');
var wordsElement = document.getElementById('words');
function addWord() {
errorElement.innerHTML = "";
var word = inputElement.value;
if (word.trim() === "")
errorElement.innerHTML = "Empty input";
else
arrayOfWord.push(word);
inputElement.value = "";
}
function process(){
words.innerHTML = arrayOfWord.join(' - ');
}
#error {
color: tomato;
}
#words {
color: purple;
}
Enter a word <input id="userinput" /><button onclick="addWord()">Add word</button>
<div id="error"></div>
<button onclick="process()">Process</button>
<div id="words"></div>
you can do something a bit clearer with jQuery! :)
if you handle the input with jquery you can write something like:
var arrWord = [] // your array
/* Attaching a click handler on your "Add Word" button that will
execute the function on user click */
$("#addWordButtonID").on("click", function () {
var wordTyped = $('#textInputID').val() // your var that collect userInput
if (wordTyped.length != 0) { // your if statement with length === 0 condition
arrWord.push(wordTyped) // adding word typed to the array
}
})
to add jquery to your html page, just add
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
in your html header
Hopefully you already have the right html. Then you can modify your script like below:
<script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
</script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
<button id="addWord" onclick="addword()">Add Word</button>
<button id="processWords" onclick="begin()">ProcessWords</button>
<input type="text" id="userinput" value=" " />
<div id="message2">
</div>
<div id="message">
</div>

Checking answer in math game won't execute

This is a math practice game I am building that is using the random function to change the math problem numbers. The user will enter the answer into a text box and then check the answer by clicking the button called "check". The fillElements() function is working however i cannot get a response from the program when i click "check". I have sorted through a lot of mistakes thus far but this problem I can not see or understand.
<body onload="fillElements()">
<form action="math.html">
<ul>
<li id="num"> </li>
<li> +</li>
<li id="num2"> </li>
<li> =</li>
<li><input type="text" name="answer" id="answer" /></li>
</ul>
<button type="button" onclick="validate()">Check</button>
</form>
<script src="javaScript/math.JS"></script>
</body>
//JavaScript
var totalCorrect= 0;
var totalIncorrect= 0;
var score = math.round(totalCorrect/totalIncorrect);
var message= 'Congrats!, you scored:' + score + 'percent';
function fillElements() {
firstNum = ['0','1','2','3','4','5','6','7','8','9'];
secondNum = ['0','1','2','3','4','5','6','7','8','9'];
var rand= Math.floor((Math.random()*9)+1);
var rand2= Math.floor((Math.random()*9)+1);
var el= document.getElementById('num');
el.textContent = firstNum[rand];
var el2= document.getElementById('num2');
el2.textContent = secondNum[rand2];
}
function validate() {
var userAnswer= number(document.getElementById('answer'));
if (num + num2 === userAnswer) {
totalCorrect++;
alert(message);
fillElements();
}
else {
totalIncorrect++;
alert(message);
}
}
It's not number() it's Number()
Check here
Working code...
HTML
<form action="math.html">
<ul>
<li id="num"></li>
<li> +</li>
<li id="num2"></li>
<li> =</li>
<li><input type="text" name="answer" id="answer" /></li>
</ul>
<button type="button" onclick="validate();">Check</button>
</form>
Javascript
window.onload = function(){
fillElements();
}
function fillElements() {
firstNum = ['0','1','2','3','4','5','6','7','8','9'];
secondNum = ['0','1','2','3','4','5','6','7','8','9'];
var rand= Math.floor((Math.random()*9)+1);
var rand2= Math.floor((Math.random()*9)+1);
var el= document.getElementById('num');
el.textContent = firstNum[rand];
var el2= document.getElementById('num2');
el2.textContent = secondNum[rand2];
}
var totalCorrect= 1;
var totalIncorrect= 1;
function validate() {
var userAnswer= Number(document.getElementById('answer').value);
var num = document.getElementById('num').textContent;
var num2 = document.getElementById('num2').textContent;
var valid = Number(num) + Number(num2);
if (valid === userAnswer) {
totalCorrect++;
var score = Math.round(totalCorrect/totalIncorrect);
var message= 'Congrats!, you scored:' + score + 'percent';
alert(message);
fillElements();
}else {
totalIncorrect++;
var score = Math.round(totalCorrect/totalIncorrect);
var message= 'Congrats!, you scored:' + score + 'percent';
alert(message);
}
}
Edit: Don't use
var totalCorrect= 0;
var totalIncorrect= 0;
because if you score a point then it will print infinity => Math.round(1/0); try
var totalCorrect= 1;
var totalIncorrect= 1;
You've to get value of input to compare, not the input itself.
So replace the following
var userAnswer= number(document.getElementById('answer'));
with
var userAnswer= number(document.getElementById('answer').value);
Javascript is case sensetive, so you need to use Math.round, not math.round:
var score = Math.round(totalCorrect/totalIncorrect);
To use the variables later, you need to declare them outside the function:
var rand, rand2;
function fillElements() {
firstNum = ['0','1','2','3','4','5','6','7','8','9'];
secondNum = ['0','1','2','3','4','5','6','7','8','9'];
rand = Math.floor((Math.random()*9)+1);
rand2= Math.floor((Math.random()*9)+1);
var el= document.getElementById('num');
el.textContent = firstNum[rand];
var el2= document.getElementById('num2');
el2.textContent = secondNum[rand2];
}
To get the value from an input you need to use the value property. To convert it to a number you use Number, not number:
var userAnswer = Number(document.getElementById('answer').value);
To check the answer, use the variables that you set before. You haven't created any variables num and num2.
if (rand + rand2 === userAnswer) {

Unable to call function within jQuery

I am trying to call a function in this javascript code. My code needs to check for whether the user selects var num, var letters and var symbols to be true or false. In the code, I preset the values but I still search the object choices for the variables that are true and push it into the array choices_made. However, since I need to randomly choose the order in which the num, letters and symbols appear, I randomly choose the class based on the Math.random(). However, it doesn't show me the alert(jumbled_result) afterwards.
http://jsfiddle.net/bdaxtv2g/1/
HTML
<input id="num" type="text" placeholder="Enter desired length">
<br/><br/>
<input id="press" type="button" value="jumble it up">
JS
$(document).ready(function(){
var fns={};
$('#press').click(function(){
var length = parseInt($('#num').val());
var num = true;
var letters = true;
var symbols = false;
gen(length, num, letters, symbols);
});
function gen(len, num, letters, sym){
var choices = {
1:num,
2:letters,
3:sym
};
var choice_made = ['0'];
var choice = 0;
var jumbled_result = '';
for(x in choices){
if(choices[x]==true){
choice_made.push(x);
}
}
for(i=0;i<len;i++){
var funName = 'choice';
choice = Math.round(Math.random() * (choice_made.length-1));
funName += choice_made[choice];
jumbled_result = fns[funName](jumbled_result);
}
alert(jumbled_result);
}
fns.choice0 = function choice0(jumbled_result){
var numbers = '0123456789';
return jumbled_result += numbers.charAt(Math.round(Math.random() * numbers.length));
}
fns.choice1 = function choice1(jumbled_result) {
var alpha = 'abcdefghijklmnopqrstuvwxyz';
return jumbled_result += alpha.charAt(Math.round(Math.random() * alpha.length));
}
});
You never declare functions within document.ready of jQuery. The functions should be declared during the first run(unless in special cases).
Here is a working code made out of your code. What I have done is just removed your functions out of document.ready event.
$(document).ready(function() {
$('#press').click(function() {
var length = parseInt($('#num').val());
var num = true;
var letters = true;
var symbols = false;
gen(length, num, letters, symbols);
});
});
var fns = {};
function gen(len, num, letters, sym) {
var choices = {
1: num,
2: letters,
3: sym
};
var choice_made = ['0'];
var choice = 0;
var jumbled_result = '';
for (x in choices) {
if (choices[x] == true) {
choice_made.push(x);
}
}
for (i = 0; i < len; i++) {
var funName = 'choice';
choice = Math.round(Math.random() * (choice_made.length - 1));
funName += choice_made[choice];
jumbled_result = fns[funName](jumbled_result);
}
alert(jumbled_result);
}
fns.choice0 = function choice0(jumbled_result) {
var numbers = '0123456789';
return jumbled_result += numbers.charAt(Math.round(Math.random() * numbers.length));
}
fns.choice1 = function choice1(jumbled_result) {
var alpha = 'abcdefghijklmnopqrstuvwxyz';
return jumbled_result += alpha.charAt(Math.round(Math.random() * alpha.length));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="num" type="text" placeholder="Enter desired length">
<br/>
<br/>
<input id="press" type="button" value="jumble it up">
Its because of the way the object choices have been intitialized.. Try this..
var choices = {
0:num,
1:letters,
2:sym
};
And also
var choice_made = [];
JS fiddle link : http://jsfiddle.net/8dw7nvr7/2/

how to change the value of input box just for display in html 5 web page

I have a textfield in which i am entering data i want that if user enter 1000 then it show 1,000 in textfield but this same value 1000 is also used in calculations further so how to solve this if user enter 1000 then just for display it show 1,000 and if we use in calcualtion then same var shows 1000 for calculating.
<HTML>
<body>
<input type="text" id="test" value="" />
</body>
<script>
var c=document.getElementById(test);
</script>
</html>
so if c user enter 1000 then it should dispaly 1,000 for dispaly one and if user uses in script
var test=c
then test should show 1000
document.getElementById returns either null or a reference to the unique element, in this case a input element. Input elements have an attribute value which contains their current value (as a string).
So you can use
var test = parseInt(c.value, 10);
to get the current value. This means that if you didn't use any predefined value test will be NaN.
However, this will be evaluated only once. In order to change the value you'll need to add an event listener, which handles changes to the input:
// or c.onkeyup
c.onchange = function(e){
/* ... */
}
Continuing form where Zeta left:
var testValue = parseInt(c.value);
Now let's compose the display as you want it: 1,000
var textDecimal = c.value.substr(c.value.length-3); // last 3 characters returned
var textInteger = c.value.substr(0,c.value.length-3); // characters you want to appear to the right of the coma
var textFinalDisplay = textInteger + ',' + textDecimal
alert(textFinalDisplay);
Now you have the display saved in textFinalDisplay as a string, and the actual value saved as an integer in c.value
<input type="text" id="test" value=""></input>
<button type="button" id="get">Get value</input>
var test = document.getElementById("test"),
button = document.getElementById("get");
function doCommas(evt) {
var n = evt.target.value.replace(/,/g, "");
d = n.indexOf('.'),
e = '',
r = /(\d+)(\d{3})/;
if (d !== -1) {
e = '.' + n.substring(d + 1, n.length);
n = n.substring(0, d);
}
while (r.test(n)) {
n = n.replace(r, '$1' + ',' + '$2');
}
evt.target.value = n + e;
}
function getValue() {
alert("value: " + test.value.replace(/,/g, ""));
}
test.addEventListener("keyup", doCommas, false);
button.addEventListener("click", getValue, false);
on jsfiddle
you can get the actual value from variable x
<html>
<head>
<script type="text/javascript">
function abc(){
var x = document.getElementById('txt').value;
var y = x/1000;
var z = y+","+ x.toString().substring(1);
document.getElementById('txt').value = z;
}
</script>
</head>
<body>
<input type="text" id="txt" value="" onchange = "abc()"/>
</body>
This works with integer numbers on Firefox (Linux). You can access the "non-commaed"-value using the function "intNumValue()":
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
String.prototype.displayIntNum = function()
{
var digits = String(Number(this.intNumValue())).split(""); // strip leading zeros
var displayNum = new Array();
for(var i=0; i<digits.length; i++) {
if(i && !(i%3)) {
displayNum.unshift(",");
}
displayNum.unshift(digits[digits.length-1-i]);
}
return displayNum.join("");
}
String.prototype.intNumValue = function() {
return this.replace(/,/g,"");
}
function inputChanged() {
var e = document.getElementById("numInp");
if(!e.value.intNumValue().replace(/[0-9]/g,"").length) {
e.value = e.value.displayIntNum();
}
return false;
}
function displayValue() {
alert(document.getElementById("numInp").value.intNumValue());
}
</script>
</head>
<body>
<button onclick="displayValue()">Display value</button>
<p>Input integer value:<input id="numInp" type="text" oninput="inputChanged()">
</body>
</html>

Categories

Resources