use this. in function

Discussion in 'JavaScript' started by crath, Jan 11, 2009.

  1. #1
    Currently, I am doing this.
    <input type="text" id="login_email" value="Email" onfocus="if(this.value==this.defaultValue){this.value=''}"/>
    Code (markup):
    And would like to place this "onfocus" code in a function, but I haven't managed to find how to do this. stuff for whatever called the function.

    I was kind of thinking I needed to do something like this.

    <script type="text/javascript">
    	function clear_input(trigger){
    		var obj = document.getElementById[trigger];
    		if(obj.value==obj.defaultValue){
    			obj.value="";
    		}
    	}
    </script>
    <input type="text" id="login_email" onfocus="clear_input(this.id)"/>
    Code (markup):
    But I wasn't quite sure about the "this.id" part, or if there was an easier method. Thanks.
     
    crath, Jan 11, 2009 IP
  2. crath

    crath Well-Known Member

    Messages:
    661
    Likes Received:
    33
    Best Answers:
    0
    Trophy Points:
    100
    #2
    got it thanks anyway

    apparently, I can send "this" as a whole to the function
     
    crath, Jan 11, 2009 IP
  3. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #3
    the better way to do things is to avoid inline onfocus= within the elements.

    i think you can assign the events in a more semantic way, at which point the function will have 'this' refer to the calling element
    
    document.getElementById("login_email").onfocus = function(e) {
        // 'this' now is automatically the login_email object, so you can do. 
        var defaultValue = this.getAttribute("defaultValue");
    ...
    }
    PHP:
    in an ideal world, write a css selector that goes through, say all input.required and applies the function to them.
    'e' should contain a reference to the event itself, useful if you want to stop it or whatever.

    i hope this helps :)
     
    dimitar christoff, Jan 12, 2009 IP
  4. crath

    crath Well-Known Member

    Messages:
    661
    Likes Received:
    33
    Best Answers:
    0
    Trophy Points:
    100
    #4
    yeah i was thinking about that, but then i didn't want to spend too much time on it, because I only have about 10 inputs.

    thanks for the tips
     
    crath, Jan 12, 2009 IP