SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Oct 2012
    Location
    California
    Posts
    34
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    getElementById issue

    I was trying to grab the 'value' of a form input with document.getElementById and noticed something strange.

    This worked fine:

    Code:
    var grab = document.getElementById("name");
    grab.value = "enter name here";
    This, however, would not work:

    Code:
    var name = document.getElementById("name");
    name.value = "enter name here";
    The problem seems to be that if the variable has the same name as the ID, it won't work. Does anyone know why this is? I looked in my JS reference book and on MDN but could not find the answer.

    Thanks!

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,788
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    Some browsers automatically map some fields from the HTML into corresponding globval variables in the JavaScript.

    The solution is to avoid using global variables in JavaScript by enclosing your script in an anonymouse self executing function.

    Code:
    (function() {
    // put your JavaScript here
    })();
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  3. #3
    SitePoint Enthusiast
    Join Date
    Jan 2010
    Posts
    51
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    to make a variable restricted to a function use this.name. You can also declare global variables within a function with window.name - "name" being the variable name.


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
  •