开发者

Rounding up values and putting it in another element

my code below does what its suppose to do with one little problem. i have sat up for hours trying to fix it. could anyone help me out please.

var price = new Array(12.121212, 45.334, 2.34, 0);

for (var i=0;i<price.length;i++){
        roundPrice[i] = Math.round(price[i]*100)/100;
    }

    var s = document.getElementsByTagName('input');
        for (var i=0;i<s.length;i++) {
            if (s[i].className == 'price') {//changed this to get class instead
                    s[i].value = roundPrice[0];
            }

        }

the line that is giving me a headache is

s[i].value = roundPrice[1];

if i state the actual inde开发者_高级运维x of the array, it puts that single value into all the input element specified.

on the other hand, if i use this line of code (below), i get 'undefined ' as a result in all the element specified.

s[i].value = roundPrice[i];

Thank you


You only have 4 values in roundPrice (which get it's values directly from price[]), and possibly more in s[], which is the input elements on the page.

Also, you are checking if the input element has an id of 'price' and only then you set the value. That should happen only once, as the id attribute is suppose to be unique for each element in the DOM.

If you only have 4 input elements in the page, and you plan on placing the values from price[] into them, remove the if (s[i].id == 'price') { and it's closing }.

Also, you should initialize your roundPrice[] array at the top with var roundPrice = new Array();.


try this:

var price = [12.121212, 45.334, 2.34, 0]
var roundPrice = [0, 0, 0, 0];

instead of your first line. PS i'm not sure whilch is the prefered way for arrays new array() or []

jsFiddle: http://jsfiddle.net/wfSWQ/

Also since you are setting an id. you could just do a `document.getElementById("price") which will return null or the element. (only 1 element). Which should work better and quicker than looping through all of them.


If I were you, I will do this, with assumption price and the input is the same

var price = new Array(12.121212, 45.334, 2.34, 0);
var s = document.getElementsByTagName('input');

for (var i=0;i<price.length;i++){
        var roundPrice = Math.round(price[i]*100)/100;

        if (s[i].id == 'price') {
                s[i].value = roundPrice;
            }

    }

Hope helps

:)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜