jQuery 如果输入值是默认值,则防止提交时出现默认值
我有一个表单,如果输入的值为默认值,我想禁用提交功能。
<input id="company" name="companyname" value="company">
<input type="submit" class="button">
我尝试了这个 jquery:
$(".button").click(function(e){
if($("#company").attr('value', 'defaultValue'))
{
alert("Please fill out the contact form.");
e.preventDefault();
}
});
但它没有按预期工作,它会按预期触发并发出警报,但也会将输入的值更改为“defaultValue”。
我很困惑:)我做错了什么?
I have a form, I want to disable the submit function if the input's value is default.
<input id="company" name="companyname" value="company">
<input type="submit" class="button">
I tried this jquery:
$(".button").click(function(e){
if($("#company").attr('value', 'defaultValue'))
{
alert("Please fill out the contact form.");
e.preventDefault();
}
});
But it doesn't work as expected, it fires and brings up the alert as intended but also changes the value of the input to "defaultValue."
I am stumped :) What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您将
value
设置为defaultValue
。这样做:谢谢 Ryan:最好使用
.val()
而不是.attr('value')
,以防当前自 HTML 属性中指定的值以来,值已更改,并且 jQuery 不会专门处理该情况。这样做:
With
You're setting the
value
todefaultValue
. Do this instead:Thanks Ryan: it's probably better to use
.val()
instead of.attr('value')
in case the current value has changed since the value specified in the HTML attribute, and jQuery doesn't handle that specially.Do this:
如果默认值只是作为更改值的提示,如果可能,请考虑使用新的 HTML5
占位符
属性。您甚至可以使用 jQuery 来帮助尚不支持它的浏览器。这样你就不需要费心检查它是否是默认值。演示:http://jsfiddle.net/Marcel/pKBMu/
If the default value is simply there as a prompt to change the value, if possible consider using the new HTML5
placeholder
attribute. You can even use jQuery to help browsers that don't support it yet. This way you don't need to bother checking if it is a default value.Demo: http://jsfiddle.net/Marcel/pKBMu/
尝试使用 .val():
http://jsfiddle.net/69HjD/2/
你'你可能想要进一步扩展它,所以也许看看 jQuery 的验证插件?
Try this with .val():
http://jsfiddle.net/69HjD/2/
You're probably going to want to extend this further so perhaps look at a validation plugin for jQuery?
是的,我知道这个问题已经得到解答,但我有一些时间,所以我编写了一个快速框架,可以让您轻松跟踪更改。基本上,这将监视表单上的所有输入元素,并在值更改时通过为它们提供一个特殊的类来直观地跟踪它们的更改。因此,用户一目了然地可以看到他们更改了什么。此外,如果没有任何输入元素发生更改,这个小框架还会阻止您发回表单。您可以通过更改选择器来扩展此框架以包含更多元素!
Right I know this has been answered but I had some time so I wrote up a quick framework that would let you track changes easily. Basically what this will do is to monitor all input elements that you have on the form and will visually track their changes by giving them a special class when the value is changed. Thus at a glance the user can see what they have changed. Further this small framework would also stop you from posting the form back if none of the input elements have changed. You can expand this framework to include more elements by changing the selector!