form input does not get saved in JavaScript function. Why? - javascript

I can not find why this does not work. "document.getElementById("number").value" won't "return" in function..
My HTML code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Currency_Converter.css">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
</head>
<body>
<div class="container">
<h1>Currency Converter</h1>
<form id="amount">Dollar amount  $<input id="number" type="number" name="number" onkeyup="getDollarAmount();" onchange="getDollarAmount();" placeholder="type dollar amount here" ></form>
</div>
</body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type='text/javascript' src="Currency_Converter.js"></script>
</html>
My JavaScript:
function getDollarAmount() {
var dollarAmount = document.getElementById("number").value;
return (dollarAmount);
}
console.log(getDollarAmount());
My "function getDollarAmount()" does not return the number put into the form. When I "console.log (dollarAmount)" I get my input. When I take out the "document.getElementById("number").value" and replace it with a number, (ex.: 5) the "getDollarAmount" function returns the number (5).
Obviously, the issue is with "document.getElementById("number").value" since the function works in every other way. What do I need to do to get "document.getElementById("number").value" to be returned to "getDollarAmount()"?

Try
var dollarAmount = $("#number").val();

The mistake here is that you are returning the value instead of assigning the dollarAmount variable to the input value attribute.
Apart from that the idea to return the converted currency value in the same place you type the amount you want to convert to is not a good practice and will be confusing.
You should have a place to input and a place to show the converted value. It's a better user experience and better for you.
You don't need jQuery. Here's an example:
var el = document.getElementById("number");
el.addEventListener("keyup", function() {
//You need to assign the value to a variable
var dollarAmount = getDollarAmount();
});
function getDollarAmount() {
return el.value;
}
<input id="number" type="number" name="number" placeholder="type dollar amount here" value="0" >
Hope it helps.

The problem is that console.log() is not getting called recursively while the value being returned by the onkeyup keeps changing.
function getDollarAmount() {
var dollarAmount = document.getElementById("number").value;
return (dollarAmount);
}
document.getElementById("number").onkeyup= () => {console.log(getDollarAmount())};

Related

Im learning JS and i have a task to make the numbers that i input reverse and pop up in an alert

i made the script that reverses the numbers but i dont know how to make the alert pop up the result of the reversed numbers
I need help to figure this out it probably has a simple solution but i dont know
The code added to snippet is below:
function okreni () { // removed "s" parameter
var a = ' ';
// s = s.toString();
const s = document.getElementById("broj").value.toString();
for (var i = s.length - 1; i>=0; i--) {
a += s[i];
}
window.alert (a);
};
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
</body>
EDIT -
The s = s.toString() has been changed to get the information from the input-value.
alert doesn't display if there's no value to display. in your case you have to passe a value to "okreni()" function.
<button value="okreni" onclick="okreni(**value**)">Okreni</button>
Apparently, you suppose to get the input value as s in okreni(s). However, this is not possible. You have to get the value programatically from the input. Following the working code. I've also created this CodeSandbox for you to try it out:
<!DOCTYPE html>
<html>
<head>`enter code here`
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="" />
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
<script type="text/javascript">
function okreni() {
var a = " ";
let inputValue = document.querySelector("#broj").value;
const s = inputValue.toString();
for (var i = s.length - 1; i >= 0; i--) {
a += s[i];
}
window.alert(a);
}
</script>
</body>
</html>
You could also try something like this to reverse your string. In looks much cleaner in my opinion and can even be condensed to a single line if needed.
Apart from that, the reason you are getting an error is because of what alexanderdavide mentioned in his answer. To elaborate further, the okreni function does not require a parameter to be passed. Instead, within the fucntion we look for the value in the input element with the id of broj. So, when you click on the button, the function checks the string in that input, reverses it and then performs an alert.
function okreni() {
let s = document.getElementById('broj').value
s = s.split("").reverse().join("")
window.alert(s)
}
<label for="broj">Unesite Broj:</label>
<input type="text" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>

str.replace(/[^0-9]/g, " ") erases my whole string instead of just getting rid of non-numerical characters. How to make it work properly?

I'm trying to use str.replace in order to remove any non-numerical characters from a number imput field when someone uses copy-pastes something in it. However the function always seems to remove all characters instead of just removing the non-numerical ones.
Surprisingly the function is able to detect when my string is purely numerical and won't change it in those cases, but adding a single other character will cause the whole string to be ditched instead of just removing the wrong characters.
I tried to change the regexp of the function to /\D/, but it didn't amount much.
Here's a minimal reproducible example, which must be run on Firefox.
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body style="margin:0px;">
<script src="../lib/jquery-3.3.1.js"></script>
<input type="number" id="inp"></input>
<script>
let input = document.getElementById("inp");
input.onblur = function()
{
$(document).ready(function()
{
input.value = input.value.replace(/[^0-9]/g, "");
});
}
</script>
</body>
</html>
I expect an output such as "34a01 2" to be "34012", but the actual output is "" (nothing). Is there something wrong in my regexp ?
let input = document.getElementById("inp");
input.onblur = function() {
$(document).ready(function() {
input.value = input.value.replace(/[^0-9]/g, "");
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="inp"></input>
This looks to be a Firefox issue (or bug). Whenever a numeric input has non-numeric characters anywhere, the .value of the field will be the empty string:
setInterval(() => {
console.log(input.value);
}, 400);
<input id="input" type="number">
It's unfortunate, but you may have to simply remove the type="number" for the .value to be retrieved and replaced as desired:
let input = document.getElementById("inp");
input.onblur = function() {
input.value = input.value.replace(/[^0-9]/g, "");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inp"></input>
Either that, or keep type="number" and tell the user that the value they attempted to paste is invalid, and prevent it (because you have no way of retrieving and replacing it).
(also: only call $(document).ready once, when you're adding the listeners, if at all - your current code is adding a new listener every time the field is blurred)
I've read your comments about Firefox and I've prepared a new version.
Not including the "number" type seems to work.
Using "number" type is not causing any issue in Chrome so I guess that Firefox is not behaving in the same way.
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body style="margin:0px;">
<script
src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8="
crossorigin="anonymous"></script>
<input id="inp"></input>
<script>
let input = document.getElementById("inp");
input.onblur = function() {
input.value = input.value.replace(/[^0-9]+/g, "");
}
</script>
</body>
</html>

Passing on a variable to a JS function from HTML

I'm currently working on a little programming task for school. I chose the task because I had an idea how to get the core of the program running in Java, but I'm having issues translating this into a very simple web page, no experience with HTML or JS.
My issue is: I'm receiving input via a button. When clicked, a function is called and that function gets the value of the input. However, all I get as the alert window is objectHTMLinputElement. What am I doing wrong?
function myRT() {
var risikoTraeger=document.getElementById('input1').value;
}
function myRH() {
var risikoHoehe = parseInt(document.getElementById('input2')).value;
alert(input2);
}
<h1>Siemens: Risikoassessment</h1>
<p id="demo">How many entries?</p>
<input type="text" id="input1" />
<button type="button" onclick="myRT()">Risk carrier</button>
<input type="text" id="input2" />
<button type="button" onclick="myRH()">Sum of the risk</button>
Get the value of the input before parsing it. Plus, you are alerting an input element instead of the variable that you are setting the value to. Use:
function myRH(){
var risikoHoehe = parseInt(document.getElementById('input2').value);
alert(risikoHoehe);
}
Change this part parseInt(document.getElementById('input2')).value; as :
parseInt(document.getElementById('input2').value)
You're calling the wrong variable, try 'risikoHoehe' instead of 'input2':
function myRT() {
var risikoTraeger=document.getElementById('input1').value;
}
function myRH(){
var risikoHoehe = document.getElementById('input2').value;
alert(risikoHoehe);
}
1) You are trying to parse a DOM element to an int so it returns undefined.
Use document.getElementById('input2').value.
2) Use parseInt only if needed, if its just for alerting then you can skip it
3) You cannot directly refer to an dom element by id, you have to get that element in a variable and then use it.
alert(input2); should be alert(risikoHoehe);
Well, Here is the complete working code-
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myRT() {
var risikoTraeger=document.getElementById('input1').value;
alert(risikoTraeger);
}
function myRH(){
var risikoHoehe = parseInt(document.getElementById('input2').value);
alert(risikoHoehe);
}
</script>
</head>
<body>
<h1>Siemens: Risikoassessment</h1>
<p id="demo">How many entries?</p>
<input type="text" id="input1" />
<button type="button" onclick="myRT()">Risk carrier</button>
</br>
<input type="text" id="input2" />
<button type="button" onclick="myRH()">Sum of the risk</button>
</body>
</html>
Hoping this will help you :)
Let's see what you are doing wrong:
var risikoHoehe = parseInt(document.getElementById('input2')).value;
document
document itself
getElementById()
the function which gives us the element that has the specific ID parameter
'input2'
the ID of the desired input
.value
the element's value if it has any.
parseInt()
the function that converts any string to it's integer value.
now look at here:
document.getElementById('input2') => the input element itself (objectHTMLInputElement)
parseInt(objectHTMLInputElement) => what can we get if we try to convert the html input element to an integer?
(integer).value => does integers have value property?
But if you write it like this:
var risikoHoehe = parseInt(document.getElementById('input2').value);
document.getElementById('input2') => the input element itself (objectHTMLInputElement)
objectHTMLInputElement.value => the value of the input as string
parseInt(string) => Parse the integer value of the string

Why does "greater than" comparison of numbers give unexpected result

There is an input field, like this,
<input class="form-control" type="number" name="recieved_by_quantity" id="quantity" />
Dynamically, a value is assigned to the input tag, like this,
document.getElementById('quantity').value = qu; //var qu=11 lets say
Now, what i want is, if the user manually inputs a value greater than "qu", then the value would automatically change itself to "qu".
What i did for this is something like,
document.getElementById('quantity').addEventListener("change", function() {
var qc = this.value;
if(qc>qu) {
this.value = qu;
}
});
The strange thing that is happening is if i input any value from 2 to infinity, it is changing all of them to 11. Only value it does not change are 0,1,10,100,1000,10000 and so on..
I am completely confused. Please help.
Its simple, use parseInt to get actual number value of your text-area.
You are getting string by default.
this.value is giving you '11'
parseInt(this.value) is giving you 11.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<input class="form-control" type="number" name="recieved_by_quantity" id="quantity" />
</body>
<script>
var qu = 11;
document.getElementById('quantity').value = qu;
document.getElementById('quantity').addEventListener("change", function() {
var qc = parseInt(this.value);
if(qc>qu) {
this.value = qu;
}
});
</script>
</html>
Use parseInt
var qc = parseInt(this.value)

Number Converter JQuery

I am a beginner and I have the following problem/code for the main body:
<body>
<form action="#">
<input type="text" id="start" />
=
<input type="text" id="finish" />
</form>
<script>
$(function() {
var cVal = $("#start").val();
var fVal = $("#finish").val();
});
</script>
</body>
With two text boxes, I would like the value entered in the celsius text box to be converted into fahrenheit in the other text box. I have tried to use the
keyup()
function but failed to produce the results I want.
typing 15 into the celsius box should result in 59 in fahrenheit. I understand that .val() does not take any arguments, so where would I do the computation for converting the numbers? And how can I incorporate keyup?
Any help is appreciated!
The val function does take arguments, you can pass it the new value and it will update textbox contents. Click the link on val, it will take you to the jQuery documentation, where all possible calls are explained. Or see the example below.
function fahrenheitToCelsius(fahrenheit) {
var val = 0;
// perform calculation
return val;
}
function celsiusToFarenheit(celsius) {
var val = 0;
// perform calculation
return val;
}
$(function() {
$("#start").on('keyup', function() {
$("#finish").val(celsiusToFarenheit($(this).val()));
});
$("#finish").on('keyup', function() {
$("#start").val(fahrenheitToCelsius($(this).val()));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
<input type="text" id="start" /> Celsius
=
<input type="text" id="finish" /> Fahrenheit
</form>
This is such a simple thing to do, jQuery is not needed at all, and because you haven't tagged jQuery here comes a plain javascript solution.
What you need to do is the add a keyup trigger on each of the input elements.
To grab our input fields we use document.getElementById(id), we use this because you've added the id attribute to your fields (it's faster than the latter method I'm mentioning). We could've used document.querySelector(selector) to get our input fields to. If you had used name="celsius" on the celsius field, we could've used document.querySelector('input[name="celsius"]') to grab that element.
What we need to do next is to an a keyup trigger to both our input fields. This is done with element.onkeyup = function() {}, in each of those functions we calculate the value for the other field.
var celsius = document.getElementById('start'),
fahrenheit = document.getElementById('finish');
celsius.onkeyup = function() {
fahrenheit.value = this.value * 9/5 + 32;
}
fahrenheit.onkeyup = function() {
celsius.value = (this.value - 32) * 5/9;
}
<form action="#">
<input type="text" id="start" /> Celsius
=
<input type="text" id="finish" /> Fahrenheit
</form>
The jQuery .val() function is an overload function which means it takes 0 up to 1 argument and it's effect varies on the number of arguments passed.
As you can see in my example calling celsiusInput.val() just returns the current value of the field. However if you use it like this farenheitOutput.val(farenheit) the current value of the input is overwritten by the variable passed.
const updateFarenheit = () => {
// find the input and output in the dom by their id
const celsiusInput = $("#start");
const farenheitOutput = $("#finish");
// get the input value
const celsius = celsiusInput.val();
const farenheit = celsius * 9 / 5 + 32;
// update the farenheit output
farenheitOutput.val(farenheit);
}
// this function runs when all js is loaded aka. "document ready"
$(document).ready(function() {
// get input field by id
const celsiusInput = $("#start");
// we pass the updateFarenheit function we defined before as the function which should run
// as soon as the keyup event occures on our celsiusInput field
celsiusInput.keyup(updateFarenheit);
});
<html lang="">
<head>
<meta charset="utf-8">
<title>Celsius to Farenheit</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form action="#">
<input type="text" id="start" /> =
<input type="text" id="finish" />
</form>
</body>
</html>

Categories