简单的 jQuery 问题 - Nil 值
我有一个表单,我正在使用 jQuery 来验证是否已在文本框中输入了正确的信息。 这工作正常,因为我有这样的代码:
var name = $("#business_name").val();
if (name == "") {
$('#namelabel').show()
$("#business_name").focus();
return false;
}
测试它是否为空,如果未填写,则会抛出错误。 我的问题是如何确定类别下拉菜单的零值。 我尝试过:
var category = $("#business_business_category_id").val();
if (category == "" || category == nil) {
$('#categorylabel').show();
$("#business_business_category_id").focus();
return false;
}
这不起作用。 我假设 nil 不是 jQuery 的正确语法,或者我不应该使用 .val 但我在网上找不到任何关于它的信息。
I have a form and I'm using jQuery to validate that the have entered in the correct information into the textboxs. That works fine, because I have this code:
var name = $("#business_name").val();
if (name == "") {
$('#namelabel').show()
$("#business_name").focus();
return false;
}
that tests to see if it is null and will throw an error if it is not filled out. My problem is how to determine the nil value of a drop down menu of categories. I tried :
var category = $("#business_business_category_id").val();
if (category == "" || category == nil) {
$('#categorylabel').show();
$("#business_business_category_id").focus();
return false;
}
Which doesn't work. I'm assuming nil is not the correct syntax for jQuery or that I shouldn't be using .val but I couldn't find anything online about it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除非“没有选择任何内容”的值不是空字符串或零,否则您可以使代码变得更简单:
这将检查 undefined、null、<强>空字符串或零。
另一件需要注意的事情是 nil 不是 JavaScript 内容/关键字。 您应该使用 undefined (或 null,但这不一样,但这是另一个讨论)
Unless the value for "nothing selected" is something else than an empty string or zero, you can make your code a lot simpler:
That will check for undefined, null, empty string or zero.
Another thing to note is that nil is not a javascript contant/keyword. You should use undefined (or null, but that's not the same, but that's another discussion)