将HTML表单输入与选择选项值相乘

时间:2017-02-25 15:19:05

标签: javascript php jquery html

我希望用户从菜单中选择特定的价格选项和数量,并自动计算总数。即(其价格)*(产品的数量或数量)。

这是代码。

请选择您的学术水平

<select name="ac_level" id="ac_level" required="">
<option id="1" value="highschool">Highschool</option>
<option id="2"value="college">College</option>
<option id="3" value="university">University</option>
<option id="4" value="masters">Masters</option>
<option id="5" value="phd">PhD</option>
</select>

页数

<input name="pages" id="number" required="" type="number" min=1 />
<input name="total" id="total" type="text" readonly />
<!-- #total = #number * #ac_level -->

1 个答案:

答案 0 :(得分:1)

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">   </script>
        <script>

            $(document).ready(function(){

                $(document).on("change","#selectboxnumbers",function(){
                    //user is user picks new option
                    var value1 =0,value2 = 0;

                    value1 = $("#selectboxnumbers option:selected").attr("value") * 1;
                    value2 = $("#value2").val() * 1;

                    if(value1 != "" && value2 != "" && value1 != "undefined" && value2 != "undefined"){
                        $("#score").html("$" + Math.round(value1 * value2));
                    }
                });
                $("input").on("keyup change",function(){
                    //user is typing so will trigger this
                    var value1 =0,value2 = 0;

                    value1 = $("#selectboxnumbers option:selected").attr("value");
                    value2 = $("#value2").val();

                    if(value1 != "" && value2 != "" && value1 != "undefined" && value2 != "undefined"){
                        $("#score").html("$" + Math.round(value1 * value2));
                    }
                });
            });
        </script>
    </head>
    <body>

        Enter Value 1: 
        <select name="ac_level" id="selectboxnumbers">
            <option id="1" value="32">Item 1 - $32</option>
            <option id="2" value="55.93">Item 2 - $55.93</option>
            <option id="3" value="88.27">Item 3 - $88.27</option>
            <option id="4" value="2">Item 4 - $2</option>
            <option id="5" value="1">Item 5 - $1</option>
        </select><br>

        Enter Value 2: <input type="number" id="value2">

        <p id="score"></p>

    </body>
</html>