running a function with onKeyDown

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • akristof
    New Member
    • Nov 2011
    • 25

    running a function with onKeyDown

    morning!

    i want to run a javascript function when I enter a key in a form text input by using onKeyDown

    everything runs perfectly except the function only executes after the 2nd key stroke (not 1st key stroke, as I would expect it to)

    maybe onKeyDown isn't the appropriate event or maybe i am doing something else wrong?

    here's my html bit

    Code:
    <input type="text" name="dogname2" class="formtextinput" id="inputter" onKeyDown="hidecontent(brad)" onBlur="unhidecontent(this)" /> 
    
    <span id="brad"> Bradd </span>
    and here's the javascript

    Code:
    function hidecontent(el) {
    	var elementcontent = document.getElementById("brad")
    	var inputtercontent = document.getElementById("inputter")
    	if (inputtercontent.value!="") elementcontent.style.cssText = "visibility:hidden"
    	
    }
    
    function unhidecontent(el) {
    	var elementcontent = document.getElementById("brad")
    	if (el.value=="") elementcontent.style.cssText = "visibility:normal"
    	
    }
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    maybe onKeyDown isn't the appropriate event
    you’re absolutely right there. onkeydown the value is not yet updated (i.e. it is still empty). use either onkeyup or onkeypress.

    Comment

    • akristof
      New Member
      • Nov 2011
      • 25

      #3
      oh duh..onkeyup worked (though in the event I press a key and keep holding it it doesn't execute the script until i release..so i get around this by using both onkeydown AND onkeyup)..thank s!

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #4
        what about onkeypress then?

        edit: it’s visibility: visible;

        Comment

        • akristof
          New Member
          • Nov 2011
          • 25

          #5
          thanks..
          onkeypress has the same problem as onkeydown
          onkeyup & onkeydown work well when i run both

          Comment

          Working...