Highlight all on focus?

Discussion in 'JavaScript' started by Triexa, Nov 6, 2006.

  1. #1
    How can I make an <input> (text) select the entire contents once it is focused? Also, I will be dynamically adding more <input>'s within the DOM so it needs to work with those too..

    I'm stumped, apart from "manually" applying it to each and every element.
     
    Triexa, Nov 6, 2006 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    
    function select_text(object)
    {
    	object.focus();
    	object.select();
    }
    
    Code (markup):
    
    <input type="text" onclick="select_text(this);" />
    
    Code (markup):
     
    nico_swd, Nov 7, 2006 IP
  3. Triexa

    Triexa Active Member

    Messages:
    580
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    53
    #3
    Is there some way to automatically apply that onclick to every input on the page, including future-created elements?
     
    Triexa, Nov 7, 2006 IP
  4. Shamsher Nawaz

    Shamsher Nawaz Peon

    Messages:
    10
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Or you can do without making any function just in the same INPUT tag.

    <input type="text" [COLOR="Red"]onclick[/COLOR]="javascript:this.select();" />
    Code (markup):
     
    Shamsher Nawaz, Nov 9, 2006 IP
  5. Triexa

    Triexa Active Member

    Messages:
    580
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    53
    #5
    I know that. That's extremely basic, and somebody already pointed out the onclick event... I was wondering if there was some way to automatically listen to every input box..
     
    Triexa, Nov 9, 2006 IP
  6. SoKickIt

    SoKickIt Active Member

    Messages:
    305
    Likes Received:
    30
    Best Answers:
    0
    Trophy Points:
    70
    #6
    for(var i=0; i<document.getElementsByTagName('input').length; i++)
    {
    	if(document.getElementsByTagName('input')[i].type == "text")
    	{
    		document.getElementsByTagName('input')[i].onfocus = function()
    		{
    			this.select();
    		}
    	}
    }
    Code (markup):
     
    SoKickIt, Nov 9, 2006 IP
  7. Triexa

    Triexa Active Member

    Messages:
    580
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    53
    #7
    Ya, that was how I was going to do it, but then I run into the issue of newly-created input boxes.

    I guess there isn't away to just automatically attach an onclick event to it...
     
    Triexa, Nov 9, 2006 IP
  8. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #8
    You can set an attribute directly when you create the new ones. Could you post the code you use to create new ones?
     
    nico_swd, Nov 9, 2006 IP