[英]How to check if form input has value
我正在尝试检查表单输入是否具有任何值(无论值是什么),以便我可以将值附加到提交时的操作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;
}
}
和形式:
<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>
我认为设置值== 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;
}
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
}
PS:它比检查value.length
更好,因为' '.length
= 3。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.