SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Jun 2010
    Posts
    34
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Problem with innerHTML

    I have a script that when a user enters something in the text field and then press "Enter" on their keyboard it will display what they've entered.
    This script works perfectly in document.writeln but when I tried to convert it into innerHTML, id does NOT work and I'm not sure why
    Code:
    <html>
    <head>
    
    <script type="text/javascript">
    
    function handleKeyPress(e,form){
       var key=e.keyCode || e.which;
       if (key==13){
          Display();
       }
    }
    
    function Display(){
      var newtext = document.myform.inputBox.value;
    
       document.writeln(newtext);
    }
    
    </script>
    </head>
    
    <body>
    
    <FORM NAME="myform">
       <input id="search" name="inputBox" type="text" value="" onkeypress="handleKeyPress(event,this.form)">
       <input id="submit" type="button" value="Submit" onClick="Display()">
    </form>
    
    </body>
    </html>

    Here's my code for innerHTML, as you can see, both codes are identical except that one uses document.writeln() and the other uses getElementById()
    Code:
    <html>
    <head>
    
    <script type="text/javascript">
    function handleKeyPress(e,form){
       var key=e.keyCode || e.which;
       if (key==13){
          Display();
       }
    }
    
    function Display(){
      var newtext = document.myform.inputBox.value;
    
       var z=document.getElementById("info");
       z.innerHTML = newtext;
    }
    
    </script>
    </head>
    
    <body>
    
    <FORM NAME="myform">
       <input id="search" name="inputBox" type="text" value="" onkeypress="handleKeyPress(event,this.form)">
       <input id="submit" type="button" value="Submit" onClick="Display()">
    </form>
    
    <p id="info"></p>
    
    </body>
    </html>
    Very confusing!!!

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,705
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by hiyatran View Post
    but when I tried to convert it into innerHTML, id does NOT work and I'm not sure why
    Your version of code with innerHTML seems to work just fine for me.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


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
  •