2012-09-20 90 views
3

我想使用preventDefault,以便当表单提交'帐号'作为输入的值时,什么都不会发生。jQuery preventDefault - 不能得到这个工作

对于我所做的所有阅读,我看不到问题。我怀疑我只是盯着它太久了,错过了一些非常明显的东西。帮我准时离开办公室!的非工作代码在这里

例子:http://jsfiddle.net/sX52r/

HTML

<form action="/" id="AccSearch" method="post">        

<input type="text" name="AccountNumber" ID="AccountNumber" class="lookup_field" value="Account number" onfocus="if(this.value=='Account number'){this.value=''}" 
onblur="if(this.value==''){this.value='Account number'}"> 

<input type="image" id="AccSearchSubmit" src="/Images/search.png" onmousedown="this.src='/Images/search_down.png'" onmouseup="this.src='/Images/search.png'" onmouseout="this.src='/Images/search.png'" alt="Submit" /> 

</form> 

JS

$('#AccSearchSubmit').click(function (e) { 
    if ($('#AccountNumber').val == 'Account number') { 
     e.preventDefault(); 
     alert("BOING!"); 
    } 
}); 
+2

不会解决你的问题,但你可能有兴趣在[jQuery的水印插件(http://code.google.com/p/jquery-watermark/)。 – jbabey

回答

4

使用提交表单的事件..使用点击( ) - 您将不得不手动处理输入按键。

$('#AccSearch').submit(function (e) { 
    if ($('#AccountNumber').val() == 'Account number') { 
     e.preventDefault(); 
     alert("BOING!"); 
    } 
}); 

你也失踪).VAL后括号(

http://jsfiddle.net/sX52r/8/

6

val是一个函数,你应该称呼它。

if ($('#AccountNumber').val() == 'Account number') { 

working jsFiddle

建议:

  • 这可能是一个更好的主意赶上形式的submit事件代替,因为在文字输入按Enter键也提交表单为例。

  • 取而代之的是“脆弱”的解决方案(包括所有的丑陋,突兀内嵌事件处理程序),你应该使用placeholder HTML5属性(所有现代浏览器都支持),以及旧的浏览器,使用插件像Mathias Bynens's jquery-placeholder

+0

在提交而不是点击时这样做很好 - 这会毫无疑问地引起我的注意。 –

+0

@AlanShortis如果您满意,请接受我的答案并在左边打勾(或者其他答案,如果您更喜欢这些答案的话)。 – kapa

0

$('#AccountNumber')。val是函数指针。要使用该值调用如下函数:

$('#AccountNumber').val(); 
1

val是jQuery对象的方法,而不是属性。更改此:

if ($('#AccountNumber').val == 'Account number') { 

这样:

if ($('#AccountNumber').val() == 'Account number') { 
//       ^^ invoke the method 
0

我只是想跟进这是我有一点空闲时间,今天和管理,以提高我的原代码。

我发现在这种情况下使用return false实际上比preventDefault更合适。关于通过按下Enter键提交表单的问题还有一个问题,那就是我正在使用的文本框的值。

无论如何,这里是我的解决方案 - 结果也变得更轻了。

http://jsfiddle.net/sX52r/22/

$('#AccSearch').submit(function() { 
if ($('#AccountNumber').val() == 'Account number' || $('#AccountNumber').val() == '') { 
alert("BOING!");    
return false; 
}});