简体   繁体   中英

Javascript function not working when called in a form tag

This is my HTML

<form> 
    <p>
        Enter the total stock value: <input id="total" type="number"onkeyup="calculate()">
    </p>
    <p>
        Enter the agreed commision rate:<input id="commision" type="number"> 
    </p>
    <p>
        <input id="calculate" type="number" readonly="readonly" placeholder="Result">
    </p> 
</form>

and this is my Javascript

calculate = function() {
    var total = document.getElementById('total').value;
    var commision = document.getElementById('commision').value; 
    document.getElementById('calculate').value = parseFloat(total) / 100 * parseFloat(commision);
}

$(document).keyup(function(e) {     
    if(e.keyCode== 27) {
        $("form")[0].reset();
    }
});

Now, if my form is not wrapped in a form tag my Calculate function works perfectly, but when it's in a form tag I'll get an error in the console saying "Uncaught TypeError: calculate is not a function". I tried without the form tag, but then the reset() function is not working..

Does anyone have any idea how to solve this issue?

那是因为你有ID计算元素,元素的IDS被复制的形式,对象的属性(也窗口属性),所以你的情况calculate已经覆盖了形式的范围内使用时,指的是DOM元素功能

<input id="txtcalculate" type="number" readonly="readonly" placeholder="Result">

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