SitePoint Sponsor

User Tag List

Results 1 to 12 of 12
  1. #1
    SitePoint Addict
    Join Date
    Jun 2007
    Posts
    396
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Checking if an input is empty?

    Hi,

    I've got a livesearch box at the moment, and would like it so if the field is empty, it'll say 'Search' kind of greyed out, but when the user clicks on it this'll disappear. I'm just wondering what the best way is of doing this please?

    Thanks

  2. #2
    SitePoint Guru alecrust's Avatar
    Join Date
    Jun 2007
    Location
    London, UK
    Posts
    728
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This is easily done. The trick is this JavaScript:
    HTML Code:
    onfocus="this.value='';"
    Add that to your input, so an end example could be:
    HTML Code:
    <input name="search-field" type="text" size="40" onfocus="this.value='';" value="Search" />
    This will have "Search" as the default value, and when it is clicked that text will disappear. This will work on all browsers.

    To make the text "greyed out" why not add this to your stylesheet, although note that it will affect all input elements (including buttons):
    Code:
    input{color:#666;}
    Honda Civic Forum - UK Civic Forum
    Web Host Reviews - Independent, honest host reviews
    My Portfolio - Simplicity is the ultimate sophistication

  3. #3
    SitePoint Wizard siteguru's Avatar
    Join Date
    Oct 2002
    Location
    Scotland
    Posts
    3,609
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Here's a proof-of-concept ...

    Code HTML4Strict:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>LiveSearch Box Test</title>
    <style type="text/css">
    .boxonload {
    	font: italic 1em Verdana, Helvetica, Arial, sans-serif;
    	color: #808080;
    }
     
    .boxonclick {
    	font: normal 1em Verdana, Helvetica, Arial, sans-serif;
    	color: #000000;
    }
    </style>
    <script type="text/javascript">
    function boxonclick (box) {
    	var el = document.getElementById (box.name);
    	el.className = 'boxonclick';
    	el.value = "";
    }
    </script>
    </head>
    <body>
    <form>
    <input class="boxonload" type="text" id="txtsearch" name="txtsearch" value="Search" onclick="boxonclick (this)" />
    </form>
    </body>
    </html>
    Ian Anderson
    www.siteguru.co.uk

  4. #4
    SitePoint Guru alecrust's Avatar
    Join Date
    Jun 2007
    Location
    London, UK
    Posts
    728
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well, there's not really any need for all this:
    Code:
    <script type="text/javascript">
    function boxonclick (box) {
        var el = document.getElementById (box.name);
        el.className = 'boxonclick';
        el.value = "";
    }
    </script>
    Since only this is needed:
    Code:
    onfocus="this.value='';"
    But yes, two replies are better than one..
    Honda Civic Forum - UK Civic Forum
    Web Host Reviews - Independent, honest host reviews
    My Portfolio - Simplicity is the ultimate sophistication

  5. #5
    SitePoint Wizard Pepejeria's Avatar
    Join Date
    Jan 2005
    Location
    Too far up north
    Posts
    1,566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Lets make it three replies...

    Revert the default value if the user doesn't type anyting into the field (changes his mind or if he is just tabbing through the page):
    Code:
    <input id="myInput" type="text" value="Search">
    
    <script type="text/javascript">
    var input = document.getElementById("myInput");
    
    input.onfocus = function() {
    	this.value = "";
    };
    
    input.onblur = function() {
    	if (this.value == "") {
    		this.value = this.defaultValue;
    	}
    };
    </script>

  6. #6
    SitePoint Enthusiast
    Join Date
    Dec 2007
    Posts
    66
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Since only this is needed:

    onfocus="this.value='';"
    Note, you are opening yourself up to a very unpleasant user experience by doing this. If the user clicks on the input field, enters a value, moves focus, then goes back to that field to:
    - Append more text
    - copy the text
    - or just put the focus there for no reason
    Then the text that he/she input will be deleted. Not good UI.

    Instead, you could first check to see if the field contains the default value, and if so, only then would you replace it. This is closer to what Pepejeria suggested, but his example suffers from the same flaw.

    Code:
    <input id="myInput" type="text" value="Search">
    <script type="text/javascript">
    var input = document.getElementById('myInput');
    input.onfocus = function() {
        if (this.value == 'Search') {
            this.value = '';
        }
    };
    input.onblur = function() {
        if (this.value == '') {
            this.value = 'Search';
        }
    };
    </script>

  7. #7
    SitePoint Wizard Pepejeria's Avatar
    Join Date
    Jan 2005
    Location
    Too far up north
    Posts
    1,566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Fotiman, good catch!

    Note that you can use this.defaultValue to get the Search string (no need to hardcode it), since that was the value set when the page loaded.

  8. #8
    SitePoint Addict
    Join Date
    Jun 2007
    Posts
    396
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Many thanks for the replies, I've made a couple of adjustments, an if statement to set the value to 'Search' from the start, but I'm not sure if this is the best way to go about it. Also, I'm changing the class to 'inactive_search' - it works okay, but my programming isn't great so if someone could check it I'd really appreciate it, just in case I've overlooked something.

    Code Javascript:
    <script type="text/javascript">
    var input = document.getElementById('live_phone');
    if (input.value == '') {input.value = 'Search'; input.className = 'inactive_search'}
    input.onfocus = function() {
    	if (this.value =='Search') {
    		this.value = '';
    		this.className = 'active_search'
    	}
    };
    input.onblur = function() {
    	if (this.value == '') {
    		this.value = 'Search';
    		this.className = 'inactive_search'
    	}
    };
    </script>

    Also, I've currently got that code inline just underneath my search box, is it okay to have it like that, or should I strive to make it 'unobtrusive' if possible? Once again, thank you very much for the information/code earlier
    Last edited by xkratosx; Jan 15, 2008 at 04:31.

  9. #9
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,527
    Mentioned
    84 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by xkratosx View Post
    I've currently got that code inline just underneath my search box, is it okay to have it like that, or should I strive to make it 'unobtrusive' if possible? Once again, thank you very much for the information/code earlier
    Yes, you should make it as unobtrusive as possible.

    The only improvement that I'd make concerns the removal of the repetitive value 'Search'.

    If the input element is given a starting value of Search, not only will that help people if javascript isn't available, but it can be used by the script as the defaultValue of the element, thus further simplifying the task at hand.

    Code HTML4Script:
    <input type="text" id="live_phone" value="Search">

    Code Javascript:
    var input = document.getElementById('live_phone');
    input.className = 'inactive_search';
    input.onfocus = function() {
        if (this.value == this.defaultValue) {
            this.value = '';
            this.className = 'active_search';
        }
    };
    input.onblur = function() {
        if (this.value == '') {
            this.value = this.defaultValue;
            this.className = 'inactive_search';
        }
    };
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  10. #10
    SitePoint Addict
    Join Date
    Jun 2007
    Posts
    396
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    That's awesome, working an absolute treat now - many thanks pmw57!

    One final question (sorry!) and I'm not sure if it justifies a new thread or not, but how would I go about making it so that if I click anywhere on the document other than on the div itself, it'll close? Much like if you click on my username over on the right, for example.

    Many thanks

  11. #11
    SitePoint Enthusiast
    Join Date
    Dec 2007
    Posts
    66
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here's one way using the Yahoo UI Library. Note, IE is has a bug where the underside of the div can be clicked and it will think it's not within that div. There is a fix, but I can't remember it off the top of my head.

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
     "http://www.w3.org/TR/html4/strict.dtd"> 
    <html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset:utf-8"> 
     <style type="text/css"> 
     div { 
       margin: 1em; 
       padding: 1px; 
       border: 1px solid #000; 
     } 
     </style> 
     <title></title> 
    </head> 
    <body> 
    <div id="container"> 
    <div>This is not it</div> 
    <div>This is not it</div> 
    <div>This is not it</div> 
    <div>This is not it</div> 
    <div>This is not it</div> 
    <div id='foo'> 
      <div>Click me</div> 
      <div>or me... 
        <div>or me!</div> 
      </div> 
    </div> 
    <div>This is not it</div> 
    <div>This is not it</div> 
    <div>This is not it</div> 
    <div>This is not it</div> 
    <div>This is not it</div> 
    </div> 
    <script type="text/javascript" src="http://yui.yahooapis.com/2.4.1/build/yahoo-dom-event/yahoo-dom-event.js"></script> 
    <script type="text/javascript"> 
    YAHOO.util.Event.on(window, 'load', function() { 
      // Create some Shorthand variables: 
      var $E = YAHOO.util.Event; 
      var $D = YAHOO.util.Dom; 
      var foo = document.getElementById('foo'); 
      $E.on(document.body, 'click', function(e) { 
        var n = $E.getTarget(e); 
        var anc; 
        // See if the event occured on or within 'foo' 
        if (n == foo) { 
          // The event occured on foo 
          // Do nothing 
        } 
        else { 
          anc = $D.getAncestorBy(n, function(el) { 
            return el == foo; 
          }); 
          if (anc == null) { 
            // The event did not occur within 'foo' so hide it 
            $D.setStyle(foo, 'display', 'none'); 
          } 
        } 
      }); 
    }); 
    </script> 
    </body> 
    </html>

  12. #12
    SitePoint Addict
    Join Date
    Jun 2007
    Posts
    396
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Many thanks, I may give that a try, although I already have the jquery library and I'm not sure if there would be conflicts?

    I'm actually using this at the moment, which I copied and messily put onto my own page, I don't fully understand how it works, but it kinda does.

    Code JAVASCRIPT:
    document.onclick=check;
     
    function check(e){
    var target = (e && e.target) || (event && event.srcElement);
    var obj = document.getElementById('live_searchbox');
    var obj2 = document.getElementById('live_name');
    checkParent(target)?obj.style.display='none':null;
    target==obj2?obj.style.display='block':null;
    }
     
    function checkParent(t){
    while(t.parentNode){
    if(t==document.getElementById('live_searchbox')){
    return false
    }
    t=t.parentNode
    }
    return true
    }


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •