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

Cho*_*hoy 6 javascript forms conditional

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

这是我的代码:

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

和形式:

<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>
Run Code Online (Sandbox Code Playgroud)

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

另外,我正在使用if语句,但我认为这是错误的代码,因为我没有其他的.也许,使用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;
}
Run Code Online (Sandbox Code Playgroud)

N 1*_*1.1 13

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
}
Run Code Online (Sandbox Code Playgroud)

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