简体   繁体   中英

JavaScript function Not Working with onchange attribute of input tag

I have been trying to replicate Duncan Donut Example from HEAD FIRST JAVASCRIPT , but the function subTotal() is never triggered by onchange event and when I look into HTML REFERENCE , I did not find any onchange event in list provided.

Duncan.html

    <html>
    <head><title>Duncan Online Donut's Service</title></head>
    <script type="text/javascript">

        function subTotal(){
            document.write("working");
            const TAXRATE = 0.095;
            const DONUTRATE = 0.5;
            var tax = 0;
            var subTotal = 0;
            var total = 0;
            var cakedonut = parseInt(document.getElementById("cakedonut").value);
            var glazedonut = parseInt(document.getElementById("glazedonut").value);

            if(isNaN(cakedonut))
                cakedonut = 0;
            if(isNaN(glazedonut))
                glazedounut = 0;

            subTotal = (cakedonut + glazedonut)* DONUTRATE ;
            tax = subTotal * TAXRATE ;
            total = subTotal + tax ;
            document.getElementById("subTotal").value = "$" + subTotal.toFixed(2);
            document.getElementById("tax").value = "$" + tax.toFixed(2);
            document.getElementById("total").value = "$" + total.toFixed(2);    
        }
    </script>
    <body>
        <h1><b><i>Duncan Online Donut's Service</i></b></h1>
        <form>
            Name : <input id="name" type="text" name="name"/><br><br>
            #no of cake donuts : <input id="cakedonut" type="text" name="cakedonut" onchange="subTotal()"/><br><br>
            #no of glazed donuts : <input id="glazedonut" type="text" name="glazedonut" onchange="subTotal("/><br><br>
            subTotal : <input id="subTotal" type="text" name="subTotal" /><br><br>
            tax : <input id="tax" type="text" name="tax" /><br><br>
            Total : <input id="total" type="text" name="total"/><br><br>
            <input type="submit"/><br><br>
        </form>
    </body>
</html>

JSFiddle

The above is my code. I tried running this on IE and Chrome but in vain. Thanks in advance.

The problem is you have defined a variable and a function both with the same name subTotal and the variable declaration is overriding the function definition. Change the function name to anything say subTotal1 it will work.

JSBIN link

change your function name. don't use subTotal(); and don't use document.write("working");

function subTotalnew()
{
alert('working');
}

onchange="subTotalnew() it gonna be work after input blur .

oninput="subTotalnew() it gonna be work when input entering something .

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