JavaScript 简单的“错误处理”通过用条件替换 NaN

发布于 2024-09-27 05:21:54 字数 2445 浏览 4 评论 0原文

我想知道如何检测错误的输入类型,而不是向用户呈现 NaN,而是显示一条逻辑信息。

这是我的代码:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>

<script>
window.onload = function() {
    document.getElementById('calculate').onclick = function calculateQuad()
    {
        var inputa = document.getElementById('variablea').value;
        var inputb = document.getElementById('variableb').value;
        var inputc = document.getElementById('variablec').value;

        root = Math.pow(inputb,2) - 4 * inputa * inputc;
        root1 = (-inputb + Math.sqrt(root))/2*inputa
        root2 = (-inputb + Math.sqrt(root))/2*inputa 

        document.getElementById('root1').value = root1;
        document.getElementById('root2').value = root2;
        if(root<'0')
        {
            document.getElementById('root1').value = 'No real solution'
            document.getElementById('root2').value = 'No real solution'
        }
        else {
            if(root=='0')
            {
                document.getElementById('root1').value = root1
                document.getElementById('root2').value = 'No Second Answer'
            }
            else {
                document.getElementById('root1').value = root1
                document.getElementById('root2').value = root1
                }
            }
    };
    document.getElementById('erase').onclick = function()
    {
        document.getElementById('form1').reset();
    }
}
</script>

<style>
#container
{
    text-align: center;
}
</style>

</head>

<body>
<div id="container">
<h1>Quadratic Root Finder!</h1>
<form id="form1">
    a:<input id="variablea" value="" type="text">
    <br/>
    b:<input id="variableb" value="" type="text">
    <br />
    c:<input id="variablec" value="" type="text">
    <br />
    <input id="calculate" value="Calculate!" type="button">
    <input id="erase" value="Clear" type="button">
    <br />
    <br />
    Roots:
    <br />
    <input id="root1" type="text" readonly>
    <br />
    <input id="root2" type="text" readonly>
</form>
</div>
</body>
</html>

所以,假设您在 b 输入字段中输入 10a,但是 a = 1c = 0 我会希望能够检测到不正确的输入,并打印“请仅输入整数”或类似的内容。

I was wondering how I can detect false input type and instead of presenting the user with NaN, have a logical piece of information be displayed.

Here is my code:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>

<script>
window.onload = function() {
    document.getElementById('calculate').onclick = function calculateQuad()
    {
        var inputa = document.getElementById('variablea').value;
        var inputb = document.getElementById('variableb').value;
        var inputc = document.getElementById('variablec').value;

        root = Math.pow(inputb,2) - 4 * inputa * inputc;
        root1 = (-inputb + Math.sqrt(root))/2*inputa
        root2 = (-inputb + Math.sqrt(root))/2*inputa 

        document.getElementById('root1').value = root1;
        document.getElementById('root2').value = root2;
        if(root<'0')
        {
            document.getElementById('root1').value = 'No real solution'
            document.getElementById('root2').value = 'No real solution'
        }
        else {
            if(root=='0')
            {
                document.getElementById('root1').value = root1
                document.getElementById('root2').value = 'No Second Answer'
            }
            else {
                document.getElementById('root1').value = root1
                document.getElementById('root2').value = root1
                }
            }
    };
    document.getElementById('erase').onclick = function()
    {
        document.getElementById('form1').reset();
    }
}
</script>

<style>
#container
{
    text-align: center;
}
</style>

</head>

<body>
<div id="container">
<h1>Quadratic Root Finder!</h1>
<form id="form1">
    a:<input id="variablea" value="" type="text">
    <br/>
    b:<input id="variableb" value="" type="text">
    <br />
    c:<input id="variablec" value="" type="text">
    <br />
    <input id="calculate" value="Calculate!" type="button">
    <input id="erase" value="Clear" type="button">
    <br />
    <br />
    Roots:
    <br />
    <input id="root1" type="text" readonly>
    <br />
    <input id="root2" type="text" readonly>
</form>
</div>
</body>
</html>

So, say for instance you type in 10a in the b input field but a = 1 and c = 0 I would like to be able to detect the incorrect input, and print "Please only input integers" or something along those lines.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

凶凌 2024-10-04 05:21:54

这很简单,这是一个完整的示例,输出漂亮的错误消息;)

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>

<script>
function getnum( id )
{   // get 'n' check number
    var input = +(document.getElementById(id).value);
    if ( isNaN( input ) )
    {
        document.getElementById('errmsg').innerHTML = 'Value of <em>' + id +'</em> is non-numeric, please enter a number.';
        return false;
    }
    return input;
}

window.onload = function() {
    document.getElementById('calculate').onclick = function calculateQuad()
    {
        var inputa = getnum('variable a');
        var inputb = getnum('variable b');
        var inputc = getnum('variable c');

        if ( inputa === false )
            return;
        if ( inputb === false )
            return;
        if ( inputb === false )
            return;

        root = Math.pow(inputb,2) - 4 * inputa * inputc;
        root1 = (-inputb + Math.sqrt(root))/2*inputa;
        root2 = (-inputb + Math.sqrt(root))/2*inputa;

        document.getElementById('root1').value = root1;
        document.getElementById('root2').value = root2;
        if(root < 0)
        {
            document.getElementById('root1').value = 'No real solution';
            document.getElementById('root2').value = 'No real solution';
        }
        else {
            if(root==0)
            {
                document.getElementById('root1').value = root1;
                document.getElementById('root2').value = 'No Second Answer';
            }
            else {
                document.getElementById('root1').value = root1;
                document.getElementById('root2').value = root1;
                }
            }
    };
    document.getElementById('erase').onclick = function()
    {
        document.getElementById('form1').reset();
    }
}
</script>

<style>
#container
{
    text-align: center;
}
#errmsg
{
    color: #c00;
}
</style>

</head>

<body>
<div id="container">
<h1>Quadratic Root Finder!</h1>
<form id="form1">
    <span id="errmsg"></span><br/>
    a:<input id="variable a" value="" type="text">
    <br/>
    b:<input id="variable b" value="" type="text">
    <br />
    c:<input id="variable c" value="" type="text">
    <br />
    <input id="calculate" value="Calculate!" type="button">
    <input id="erase" value="Clear" type="button">
    <br />
    <br />
    Roots:
    <br />
    <input id="root1" type="text" readonly>
    <br />
    <input id="root2" type="text" readonly>
</form>
</div>
</body>
</html>

It's rather simple, Here is a complete sample, outputting beautiful error messages to ;)

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>

<script>
function getnum( id )
{   // get 'n' check number
    var input = +(document.getElementById(id).value);
    if ( isNaN( input ) )
    {
        document.getElementById('errmsg').innerHTML = 'Value of <em>' + id +'</em> is non-numeric, please enter a number.';
        return false;
    }
    return input;
}

window.onload = function() {
    document.getElementById('calculate').onclick = function calculateQuad()
    {
        var inputa = getnum('variable a');
        var inputb = getnum('variable b');
        var inputc = getnum('variable c');

        if ( inputa === false )
            return;
        if ( inputb === false )
            return;
        if ( inputb === false )
            return;

        root = Math.pow(inputb,2) - 4 * inputa * inputc;
        root1 = (-inputb + Math.sqrt(root))/2*inputa;
        root2 = (-inputb + Math.sqrt(root))/2*inputa;

        document.getElementById('root1').value = root1;
        document.getElementById('root2').value = root2;
        if(root < 0)
        {
            document.getElementById('root1').value = 'No real solution';
            document.getElementById('root2').value = 'No real solution';
        }
        else {
            if(root==0)
            {
                document.getElementById('root1').value = root1;
                document.getElementById('root2').value = 'No Second Answer';
            }
            else {
                document.getElementById('root1').value = root1;
                document.getElementById('root2').value = root1;
                }
            }
    };
    document.getElementById('erase').onclick = function()
    {
        document.getElementById('form1').reset();
    }
}
</script>

<style>
#container
{
    text-align: center;
}
#errmsg
{
    color: #c00;
}
</style>

</head>

<body>
<div id="container">
<h1>Quadratic Root Finder!</h1>
<form id="form1">
    <span id="errmsg"></span><br/>
    a:<input id="variable a" value="" type="text">
    <br/>
    b:<input id="variable b" value="" type="text">
    <br />
    c:<input id="variable c" value="" type="text">
    <br />
    <input id="calculate" value="Calculate!" type="button">
    <input id="erase" value="Clear" type="button">
    <br />
    <br />
    Roots:
    <br />
    <input id="root1" type="text" readonly>
    <br />
    <input id="root2" type="text" readonly>
</form>
</div>
</body>
</html>
不及他 2024-10-04 05:21:54

您可以在尝试在计算中使用输入之前检查输入。

document.getElementById('calculate').onclick = function calculateQuad() {
    var inputa = document.getElementById('variablea').value;
    var inputb = document.getElementById('variableb').value;
    var inputc = document.getElementById('variablec').value;

    inputa = new Number(inputa); // try to convert to number
    if (isNaN(inputa)) { // use built in method to check for NaN
        alert('variable a is not a valid integer or whatever.');
        return;
    }

    // TODO repeat for b and c

    root = Math.pow(inputb, 2) - 4 * inputa * inputc;
    root1 = (-inputb + Math.sqrt(root)) / 2 * inputa; // don't forget your semicolons.
    root2 = (-inputb + Math.sqrt(root)) / 2 * inputa;

    document.getElementById('root1').value = root1;
    document.getElementById('root2').value = root2;

    // should be comparing against integer 0, not string 0
    if (root < 0) {
        document.getElementById('root1').value = 'No real solution'
        document.getElementById('root2').value = 'No real solution'
    }
    else {
        if (root === 0) {
            document.getElementById('root1').value = root1
            document.getElementById('root2').value = 'No Second Answer'
        }
        else {
            document.getElementById('root1').value = root1
            document.getElementById('root2').value = root1
        }
    }
};

You can check the input before you try to use it in a calculation.

document.getElementById('calculate').onclick = function calculateQuad() {
    var inputa = document.getElementById('variablea').value;
    var inputb = document.getElementById('variableb').value;
    var inputc = document.getElementById('variablec').value;

    inputa = new Number(inputa); // try to convert to number
    if (isNaN(inputa)) { // use built in method to check for NaN
        alert('variable a is not a valid integer or whatever.');
        return;
    }

    // TODO repeat for b and c

    root = Math.pow(inputb, 2) - 4 * inputa * inputc;
    root1 = (-inputb + Math.sqrt(root)) / 2 * inputa; // don't forget your semicolons.
    root2 = (-inputb + Math.sqrt(root)) / 2 * inputa;

    document.getElementById('root1').value = root1;
    document.getElementById('root2').value = root2;

    // should be comparing against integer 0, not string 0
    if (root < 0) {
        document.getElementById('root1').value = 'No real solution'
        document.getElementById('root2').value = 'No real solution'
    }
    else {
        if (root === 0) {
            document.getElementById('root1').value = root1
            document.getElementById('root2').value = 'No Second Answer'
        }
        else {
            document.getElementById('root1').value = root1
            document.getElementById('root2').value = root1
        }
    }
};
送舟行 2024-10-04 05:21:54

我认为你需要这样的东西

    function NaNValueReplacement() {
for (var i = 0; i < arguments.length; i++) {
    //alert(arguments[i]);
      var x = (arguments[i]);
      var y = document.getElementById(x).value; 
      var y_txtField = document.getElementById(x);
   /*
   alert('Argument '+i+'  with name "'+x+'"   :::   Value of element '+i+' is "'+y+'"   and the variable type is "'+y_txtField+'"');
   */
     if ( isNaN(y))
    {
        y_txtField.value='Some Other Value';

    }

}}

并这样称呼它:
NaNValueReplacement('txt_field_1','txt_field_2','txt_field_3','txt_field_4');

您可以根据需要放置任意数量的 txt_field。

我还在这里放置了一个示例 http://jsfiddle.net/lidakis/mveWy/6/

希望有帮助。

I think that you need something like this

    function NaNValueReplacement() {
for (var i = 0; i < arguments.length; i++) {
    //alert(arguments[i]);
      var x = (arguments[i]);
      var y = document.getElementById(x).value; 
      var y_txtField = document.getElementById(x);
   /*
   alert('Argument '+i+'  with name "'+x+'"   :::   Value of element '+i+' is "'+y+'"   and the variable type is "'+y_txtField+'"');
   */
     if ( isNaN(y))
    {
        y_txtField.value='Some Other Value';

    }

}}

And Call it like this:
NaNValueReplacement('txt_field_1','txt_field_2','txt_field_3','txt_field_4');

You can place as many txt_fields as you want.

Also I have placed an example here http://jsfiddle.net/lidakis/mveWy/6/

Hope It Helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文