0

this is my javascript code :

var strp = [0,19,26,33,40,46,49,57,61,65,67,73,76];
var i = document.getElementById("length").value;
function calculator(){

    document.write("the total cost is " + strp[document.getElementById("length").value]);

     document.write("total is ");
     document.write(strp[i]);   
}

i am trying to write a calculating function here. and html part is this:

<form>         
    select size   : <select id="length">
                    <option value="0">Please Choose One...</option>
                    <option value="1">10 inches</option>
                    <option value="2">12 inches</option>
      </select>
    <input type="button" value="Calculate" onclick="calculator()" />
</form>

When i am executing this code in browser, I am accessing array by 'getelementbyid value' and i am getting the correct answer. But when i am storing the getelmentbyid value in a variable , and using the the variable to access the array, the output is undefined why is that?

4

2 回答 2

1

My guess is i is undefined because the javascript is rendering before the html. So, when i is created, there is no element with id length yet. Try putting the javascript below the html to fix this.

于 2013-06-06T18:14:13.487 回答
1

It's the document.write() wiping out all the previous content of the page. Please use some proper DOM manipulation method like innerHTML or appendChild() instead.

于 2013-06-06T18:16:11.653 回答