javascript variables and string concatenation

Discussion in 'JavaScript' started by forumposters, Mar 21, 2007.

  1. #1
    Can someone please tell me what is wrong with the javascript below.

    function imageDescSwap(imageDesc, jobid) {
    document.getElementById('imageDescArea+jobid+').innerHTML = imageDesc ;
    }

    Here's the error message that occurs when this is run:
    document.getElementById("imageDescArea+jobid+") has no properties

    Obviously, the jobid is not being interpreted as a variable as I want it too, but as a string instead.
     
    forumposters, Mar 21, 2007 IP
  2. Adi

    Adi Peon

    Messages:
    23
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    try this:
    document.getElementById(eval('imageDescArea'+jobid)).innerHTML = imageDesc;
    }

    or :
    idStr = 'imageDescArea' + jobid ;
    var obj = document.getElementById(idStr);
    if (obj != null)
    obj.innerHTML = imageDesc ;

    notes
    1. Make sure to check for null value before using the return value of getElementById (or any function like it)
    2. If your code has many many "document.getElementById()" consider replacing it with a shorter function name like :
    function GID(id)
    {
    return document.getElementById(id);
    }

    this will make your page size smaller. :)
     
    Adi, Mar 21, 2007 IP