我有这段代码:
First name:
<input id="first_name" name="firstname" type="text" placeholder="First Name" />
Last name:
<input id="last_name" name="lastname" type="text" placeholder="Last Name" />
<input id="search_order" type="Submit" value="Find Order" />
<span id="warning" style="visibility: hidden; color: red;">Please enter first and last name</span>
<script>
document.getElementById("search_order").addEventListener("click", search);
function search() {
var fname = document.getElementById("first_name").value;
var lname = document.getElementById("last_name").value;
var name = fname + " " + lname;
if (fname == " " || lname == " ")
{
document.getElementById("warning").style.visibility = "visible";
return;
} else
window.location = "http://bifoldsbidesign.com/?s=" + name + "&post_type=project";
}
</script>
即使使用If语句检查值是否为空,其中的搜索总是会经历?
如果有任何帮助,代码会在网站http://bifoldsbidesign.com/search-for-your-order/上生效。
答案 0 :(得分:0)
如果您打算检查firstname
和lastname
是否为空,则应将其与""
进行比较,而不是" "
。后者在两个引号之间有一个空格。
First name:
<input id="first_name" name="firstname" type="text" placeholder="First Name" /> Last name:
<input id="last_name" name="lastname" type="text" placeholder="Last Name" />
<input id="search_order" type="Submit" value="Find Order" />
<span id="warning" style="visibility: hidden; color: red;">Please enter first and last name</span>
<script>
document.getElementById("search_order").addEventListener("click", search);
function search() {
var fname = document.getElementById("first_name").value;
var lname = document.getElementById("last_name").value;
var name = fname + " " + lname;
if (fname == "" || lname == "") {
document.getElementById("warning").style.visibility = "visible";
return;
} else
window.location = "http://bifoldsbidesign.com/?s=" + name + "&post_type=project";
}
</script>
&#13;
答案 1 :(得分:0)
将您的条件更改为
if (fname.trim() == "" || lname.trim() == "")
您的条件将检查" "
空格而不是空字符串。您也可以使用trim()不允许空格
document.getElementById("search_order").addEventListener("click", search);
function search() {
var fname = document.getElementById("first_name").value;
var lname = document.getElementById("last_name").value;
var name = fname + " " + lname;
if (fname.trim() == "" || lname.trim() == "")
document.getElementById("warning").style.visibility = "visible";
else
window.location = "http://bifoldsbidesign.com/?s=" + name + "&post_type=project";
}
&#13;
First name:
<input id="first_name" name="firstname" type="text" placeholder="First Name" />
Last name:
<input id="last_name" name="lastname" type="text" placeholder="Last Name" />
<input id="search_order" type="Submit" value="Find Order" />
<span id="warning" style="visibility: hidden; color: red;">Please enter first and last name</span>
&#13;
答案 2 :(得分:0)
您正在检查字段是否包含空格。你想要fname.trim() == ""
其中trim()
首先删除所有空白字符,然后检查空字符串。
您还应将name
的作业移至实际使用的其他作用域。