简体   繁体   中英

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

   $(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() .

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. You could also use $(this) to reference the textbox, as within that function this refers to the textbox DOM element itself. Wrapping it with the jQuery function $() gives you access to all the framework's goodies.

$(document).ready(function()
{
    $('#startDateBox').click(function(){  
         if($(this).val() == 'Beginning')
                 ^^^^^^ Here
         {
             $(this).val(''); 
         }
    })
});​ 

I would suggest for HTML5 browsers use this

 <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...

I think you meant something more like:

if($('#startDateBox').val() == 'Beginning')

I wrote a very small jquery plugin for this purpose recently:

https://gist.github.com/rmcvey/5136582

$('#input').placeholder("Placeholder Text");

if($('#input').val() === $('#input').placeholder()){ return false; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM