Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
862 views
in Technique[技术] by (71.8m points)

html - Javascript object is not a function

I get the following error and I can't find why:

TypeError: object is not a function

Here is my html:

<td><input type="text" value="" id="cash_retained" name="cash_retained" onkeyup="net_cash()" size="25"></td>
<td><input type="text" value="" id="cash_change" name="cash_change" onkeyup="net_cash()" size="25"></td>
<td><input type="text" value="0" id="net_cash" name="net_cash"></td>

Here is my js function:

function net_cash() {
    var cash = 0;
    var retained = document.getElementById("cash_retained");
    var change = document.getElementById("cash_change");

    cash += parseInt(retained.value);
    cash += parseInt(change.value);

    if (isNaN(cash)) {
        document.getElementById("net_cash").value = "0";
    } else {
        document.getElementById("net_cash").value = cash;
    }
}

I can't see for the life of me why this is not working. I have other similar js functions that are finding it just fine.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It appears the problem here is that you have a form element with the same name as your function:

<td><input type="text" value="0" id="net_cash" name="net_cash"></td>

So when you call net_cash() in your onkeyup event, it thinks you are referring to this input DOM object rather than the function of the same name. I suggest coming up with separate names for these two things.

Inline event handlers have the enclosing <form> element as their executing scope. Each form control with a name attribute is treated as though it's a variable in that scope and that's where the conflict comes from.

This is also yet another great reason to use unobtrusive JavaScript instead of inline event handlers. If you do that, you don't have to worry about your function names conflicting with your element names. See onclick=“” vs event handler for more information on the pitfalls of using inline event handlers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...