简体   繁体   中英

Passing variable values into javascript from html form

I can't seem to get this to work and I've tried quite a bit. I have a jscript file that contains a very long and involved function that does various calculations. I am trying to pass values for variables that exist within the jscript file. The jscript file contains 3 variables that I would like to have the ability to change from the HTML forms page.

The variables within the jscript file that I am trying to change are vehicleWeight, wheelbase, and tireChoice. Note that the jscript file works flawlessly but I'd like to be able to change the variables without going in and manually saying var vehicleWeight = 300, etc. The function I am running in framework.js is Main.

This is what my HTML page looks like.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Untitled Page</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    <script type="text/javascript" src="framework.js"></script>
    <script type="text/javascript">
        function ShowCalculation() {
            Main($("#wheelBaseTxt").val(), $("#tireChoiceSel").val(), $("#wheelBaseTxt").val());
        }
    </script>
</head>
<body>
    Vehicle Weight:
    <input id="vehicleWeightTxt" type="text" /><br />
    Tire Choice:
    <select id="tireChoiceSel">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select><br />
    Wheel Base: <input type="text" id="wheelBaseTxt" /><br />
    <input type="submit" onclick="ShowCalculation(); return false;" />
</body>
</html>

Its hard to say without viewing your javascript include but you may need something similar to the code below inside your Main function.

var vehicleWeight = 0.0;
var wheelbase = 0.0;
var tireChoice = 0.0;
function Main(inpVehicleWeight, inpWheelbase, inpTireChoice) {
   vehicleWeight = inpVehicleWeight;
   wheelbase = inpWheelBase;
   tireChoice = inpTireChoice;

   // ... other calculations, etc ...

}

除非框架js中定义的变量是全局变量,否则您无法更改它们的值。

I did this:

<script type="text/javascript">
        function ShowCalculation() {
            alert($("#wheelBaseTxt").val()  + "; " +  $("#tireChoiceSel").val()  + "; " +  $("#wheelBaseTxt").val());
        }
</script>

...and it does not seem to be a problem with jQuery... the values are there. Use this approach to test. The problem may be within the Main() function.

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