[英]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.