简体   繁体   中英

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

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 &ensp;$<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()"?

尝试

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM