How to check if form input has value(如何检查表单输入是否有价值)
问题描述
我正在尝试检查表单输入是否有任何值(无论该值是什么),以便我可以将该值附加到提交时的操作 URL(如果它确实存在).我需要在添加值之前添加参数的名称,并且只留下一个空白的参数名称,如P =",没有任何值会弄乱页面.
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.
这是我的代码:
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>
我认为设置 value == 1 会做一个简单的存在,不存在检查,不管提交的值是什么,但我想我错了.
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.
另外,我正在使用 if 语句,但我认为这是糟糕的代码,因为我没有 else.也许,使用 switch 语句,虽然我不确定我将如何设置它.也许:
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:
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
}
P.S.:它比检查 value.length 更好,因为 ' '.length = 3.
P.S.: Its better than checking against value.length because ' '.length = 3.
这篇关于如何检查表单输入是否有价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检查表单输入是否有价值
基础教程推荐
- Bootstrap 模态出现在背景下 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
