所以我有这个代码,我说if website_name===""
显示错误,但它似乎不起作用,因为如果我输入内容并将其删除以便它为空它仍会显示它&#39 ; s有效所以它运行else语句,但是如果我键入一个数字然后我得到一个错误,但我需要它也适用于空值。
var message;
var inputField = document.getElementById("website_name");
$( "#website_name" ).keyup(function() {
if(website_name==="" || !/^[a-z]*$/.test(this.value))
{
$("#website_name").css('border', '3px solid red');
inputField.style.backgroundColor = "#f27676";
message = 'Only lower case characters allowed!';
$('div.modal-body .msgPlaceholder').empty().append(message);
}else{
$("#website_name").css('border', '3px solid green');
inputField.style.backgroundColor = "#56c145";
message = 'Your name is correct';
$('div.modal-body .msgPlaceholder').empty().append(message);
}
});
答案 0 :(得分:6)
您必须使用this.value == ""
而不是website_name == ""
,因为website_name
不是variable
如果您想在检查之前使用toLowerCase
,请尝试以下操作:
var val = this.value.toLowerCase();
if (val == "")
var message;
var inputField = document.getElementById("website_name");
$("#website_name").keyup(function() {
if (this.value == "" || !/^[a-z]*$/.test(this.value)) {
$("#website_name").css('border', '3px solid red');
inputField.style.backgroundColor = "#f27676";
message = 'Only lower case characters allowed!';
$('div.modal-body .msgPlaceholder').empty().append(message);
} else {
$("#website_name").css('border', '3px solid green');
inputField.style.backgroundColor = "#56c145";
message = 'Your name is correct';
$('div.modal-body .msgPlaceholder').empty().append(message);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="website_name" />