Javascript 如何检查表单输入是否有价值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2588229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:02:50  来源:igfitidea点击:

How to check if form input has value

javascriptformsconditional

提问by Choy

I'm trying to check if a form input has any value (doesn't matter what the value is) so that I can append the value to the action URL on submit if it does exist. I need to add the name of the param before adding the value, and just leaving a blank param name like "P=" without any value messes up the page.

我正在尝试检查表单输入是否有任何值(与值无关),以便我可以在提交时将该值附加到操作 URL(如果它确实存在)。我需要在添加值之前添加参数的名称,并且只留下一个空白的参数名称,例如“P=”而没有任何值会弄乱页面。

Here's my code:

这是我的代码:

function getParam() {

// reset url in case there were any previous params inputted

    document.form.action = 'http://www.domain.com'

    if (document.getElementById('p').value == 1) {
        document.form.action += 'P=' + document.getElementById('p').value;
    }

    if (document.getElementbyId('q').value == 1) {
        document.form.action += 'Q=' + document.getElementById('q').value;
    }

}

and the form:

和形式:

<form name="form" id="form" method="post" action="">
    <input type="text" id="p" value="">
    <input type="text" id="q" value="">
    <input type="submit" value="Update" onClick="getParam();">
</form>

I thought setting value == 1 would do a simple exists, doesn't exist check regardless of what the submitted value was, but I guess I'm wrong.

我认为设置 value == 1 会做一个简单的存在,不存在检查无论提交的值是什么,但我想我错了。

Also, I'm using if statements, but I believe that's bad code, since I don't have an else. Perhaps, using a switch statement, though I'm not sure how I would set that up. Perhaps:

另外,我正在使用 if 语句,但我认为这是糟糕的代码,因为我没有 else。也许,使用 switch 语句,尽管我不确定如何设置。也许:

switch(value) {
    case document.getElementById('p').value == 1 :
        document.form.action += 'P=' + document.getElementById('p').value; :
    case document.getElementById('q').value == 1 :
        document.form.action += 'Q=' + document.getElementById('q').value; break;
}

回答by N 1.1

var val = document.getElementById('p').value;
if (/^\s*$/.test(val)){
   //value is either empty or contains whitespace characters
   //do not append the value
}
else{
   //code for appending the value to url
}

P.S.: Its better than checking against value.lengthbecause ' '.length= 3.

PS:它比检查更好,value.length因为' '.length= 3。