简体   繁体   中英

eval(document.getElementById(“userinput”).value) not working

I have a input element that holds a mathematical expression in string form in its value attribute (ie "3+5-6*8")

I want to evaluate this value and then set it as the new value for the input element.

this is my JS function:

    function evaluate() {
            document.getElementById("userinput").value=eval(document.getElementById("userinput").value);
        }

for some reason, this does not do anything

According to my knowledge, eval() only works if the argument is a string; otherwise it will return the argument unchanged.

The data type of the value attribute of the input element should be a string according to the way i made the input tag:

    <input type="text" id="userinput" readonly="true">

what is wrong?

Are you getting the error: Uncaught NotSupportedError: Failed to execute 'evaluate' on 'Document': The context node provided is null. ?

The problem is that evaluate is kind of a keyword that shouldn't be overridden: https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript

So I renamed the function to foo , and it worked: http://jsfiddle.net/28sXE/1/

html:

<input type="text" id="userinput" />
<button onClick="foo()">do it</button>

js:

function foo() {
    var val = document.getElementById("userinput").value;
    var out = eval(val);
    document.getElementById("userinput").value = out;
}

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