[英]Clear input box on click with Jquery
I have a simple code that I'm trying to wrok into my website to clear a textbox with a default value, when a user click on it, the default value should clear out so that the user can enter his/her value. 我有一个简单的代码,试图插入到我的网站中以清除带有默认值的文本框,当用户单击它时,默认值应清除掉,以便用户可以输入他/她的值。 Here is what I have but I'm not sure if its correct since its not working.
这是我所拥有的,但是由于其不起作用,因此我不确定其是否正确。 I just started on JQuery
我刚开始使用JQuery
$(document).ready(function()
{
$('#startDateBox').click(function()
{
if(('#startDateBox')=='Beginning')
{
$('#startDateBox').val('');
}
})
});
You're wrong in this part: 您在这部分上是错误的:
if(('#startDateBox')=='Beginning')
First, you missing $
. 首先,您缺少
$
。 Second, I think you want compare the startDateBox
value, then use val()
. 其次,我认为您想比较
startDateBox
值,然后使用val()
。
Try this: 尝试这个:
$(document).ready(function()
{
$('#startDateBox').click(function()
{
if($('#startDateBox').val()=='Beginning')
{
$('#startDateBox').val('');
}
})
});
You missed the first .val()
, and the $
in front of the ('#startDateBox')
on the same line. 您错过了第一个
.val()
和同一行中('#startDateBox')
前面的$
。 You could also use $(this)
to reference the textbox, as within that function this
refers to the textbox DOM element itself. 您也可以使用
$(this)
引用文本框,因为在该函数中, this
引用文本框DOM元素本身。 Wrapping it with the jQuery function $()
gives you access to all the framework's goodies. 用jQuery函数
$()
包装它可以使您访问所有框架的功能。
$(document).ready(function()
{
$('#startDateBox').click(function(){
if($(this).val() == 'Beginning')
^^^^^^ Here
{
$(this).val('');
}
})
});
I would suggest for HTML5 browsers use this 我建议HTML5浏览器使用此功能
<input type="text" id="Beginning" placeholder="Beginning" />
if($('#startDateBox').val() =='Beginning')
this is the line that needs to be changed 这是需要更改的行
also 也
$('#startDateBox').on("focus", function()
{
// code here
the click will not handle hitting tab until that text box is focused 在该文本框处于焦点状态之前,单击不会处理点击选项卡
Well, if(('#startDateBox')=='Beginning')
will always be false... 好吧,
if(('#startDateBox')=='Beginning')
永远是假的...
I think you meant something more like: 我认为您的意思更像是:
if($('#startDateBox').val() == 'Beginning')
I wrote a very small jquery plugin for this purpose recently: 我最近为此目的编写了一个非常小的jquery插件:
https://gist.github.com/rmcvey/5136582 https://gist.github.com/rmcvey/5136582
$('#input').placeholder("Placeholder Text");
if($('#input').val() === $('#input').placeholder()){ return false; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.