javascript - Why is parseInt not working for me? -
no matter try nan when try parse input value variable. trying make calculator determine fuel economy.
<!doctype html> <html> <head> <title>fuel calculator</title> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge,chrome=1"> <meta name="description" content="demo project"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"> <link rel="stylesheet" href="style.css"> <style type="text/css"></style> </head> <body> <div class="wrapper"> <h1>fuel usage</h1> <div class="row"> <div class="col-md-12"> <form> <div class="form-group"> <label>miles driven per year</label> <input type="text" class="form-control" id="mpy"> </div> <div class="form-group"> <label>mpg</label> <input type="text" class="form-control" id="mpg"> </div> <p>gallons used: <span id="used"></span</p> <div class="form-group"> </div> <button id="submit" type="submit" class="btn btn-default">submit</button> </form> </div> </div> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script src="main.js" type="text/javascript"></script> </body> </html> js file
var mpy = parseint($('#mpy').val(), 10); var mpg = parseint($('#mpg').val(), 10); var gallonsused = mpy/mpg; $('#submit').click(function(){ $('#used').text(gallonsused); });
since have input fields declared globally, initial value in text value empty. result of parseint give nan value.
need calculate parsed values once invoke click event.
$('#submit').click(function(e){ var mpy = parseint($('#mpy').val(), 10); var mpg = parseint($('#mpg').val(), 10); var gallonsused = mpy/mpg; $('#used').text(gallonsused); }); working example : https://jsfiddle.net/dinomyte/b9bhs4s3/
Comments
Post a Comment