Search code examples
jquerydefault-valuetextinput

How to change the text input value to none in this existing project upon focus, in jquery


I have this so far: http://jsfiddle.net/26eVE/4/

I want that when the user clicks on the small input field (that one with value 1 as default), the value changes from 1 to "".

EDIT: Also after the focus is not on the input (the user clicks somewhere else after clicking in the input), show the default value 1 if the user didn't type anything inside the text input, otherwise keep the input he typed in.


Solution

  • You have a bug in your html, you're missing the = in the class attribute.

     <input type="text" value="1" class="item_input" /> 
    

    Something like this is all you need.

        // Remove and store on focus
        // Restore if empty on blur 
        $('.item_input')
                .focus(function(e) { 
                        var $this = $(this);
                        $this.data('lastValue', $this.val()).val(''); 
                })
                .blur(function(e) { 
                        var $this = $(this);
                        if($this.val()=='') $this.val($this.data('lastValue')); 
                });