Results 1 to 2 of 2

Thread: document.getElementById issue

  1. #1
    Join Date
    Apr 2006
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default document.getElementById issue

    I'm have a issue here. The "addnumb" is 25 and I'm trying to add it to the value of document.getElementById(total).innerHTML with is 1.95, but the alert box just appends the 25 to the end. The result is $1.9525. What am I doing wrong here. I've been at this for about 6 hrs now. Please help.

    <div id="total">1.95</div>
    function addCostBox(boxName,total,addnumb){
    if(boxName.checked) {
    var g = document.getElementById(total).innerHTML;
    var a = g;
    var b = addnumb;
    var d = a + b;
    alert('This option will add $'+d+' to your total.');
    }
    }

    Thanks,
    Shane

  2. #2
    Join Date
    Dec 2004
    Location
    UK
    Posts
    2,358
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by svoirin
    The "addnumb" is 25 and I'm trying to add it to the value of document.getElementById(total).innerHTML with is 1.95, but the alert box just appends the 25 to the end.
    As the innerHTML property evaluates to a string, the other operand is type-converted to a string, too. The result is concatenation rather than arithmetic addition.

    Code:
    function addCostBox(boxName, total, value) {
      var element;
    
      if (boxName.checked && document.getElementById
          && (element = document.getElementById(total))) {
        alert('This option will add $'
            + (+element.innerHTML + value)
            + ' to your total.');
      }
    }
    The unary plus (+) in the expression,

    Code:
    +element.innerHTML
    coerces its operand to a number or NaN (Not-a-Number).

    Mike

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
  •