如何查找输入字段中的正数和负数的数量

How to find the number of positive and negative numbers are there on an input field?

本文关键字:字段 何查找 查找 输入      更新时间:2023-09-26

我的问题是有 3 个输入文本字段和一个按钮,无论用户输入并按下按钮,警报都应该说明文本字段上有多少负数和多少正数?

这是一个工作示例 代码解释如下。

如果您想在每个文本字段中输入一个数字,然后单击告诉输入的正号和负号数的按钮,那么这是您的代码,

你的 HTML 代码,

<input id="one" type="text"/>
<input id="two" type="text"/>
<input id="three" type="text"/>
<input type="button" onclick="check();" value="check">

现在您可以按如下方式编写脚本,

function check(){
    //Converting the values to integer
    var x = parseInt(document.getElementById("one").value);
    var y = parseInt(document.getElementById("two").value);
    var z = parseInt(document.getElementById("three").value);
    //Initializing the positive and negative count to 0 
    var posCount = 0;
    var negCount = 0;
    //Incrementing postive and negative count depending whether it is      positive or negative
    if(x>=0){
        posCount++;
    }else{
        negCount++;
    }
    if(y>=0){
        posCount++;
    }else{
        negCount++;
    }
    if(z>=0){
        posCount++;
    }else{
        negCount++;
    }
    alert("Positive numbers: "+posCount);
    alert("Negative numbers: "+negCount);
}