用于多个文本框的javascript

时间:2012-02-15 18:53:02

标签: javascript for-loop

我有10个文本框,名称为qty1-10,price1-10和total1-10。我正在做的是添加qty1 + price1 = total1,qty2 + price2 = total2等的值。

这是我目前的代码 -

function Add()
  {
    var qty1 = document.getElementById('qty1').value; 
    var u_price1 = document.getElementById('price1').value; 
    if (qty1 == "") {
        if (u_price1 == "") {
            document.form1.total1.value = "null";
            return;
            }
        document.form1.total1.value = "null";
        return;
        }
    else
    {
       document.form1.total1.value = Number(qty1) + Number(u_price1);
    }    
  }

现在我想编写一个for循环,它将使用相同的代码,但将qty1的名称更改为qty2,依此类推。

2 个答案:

答案 0 :(得分:1)

您可以将类分配给这些文本框,然后执行

var arr = document.getElementByClassName('classname')

您将获得可以申请循环的文本框数组,然后在循环中执行代码。

(我不是在编写代码,因为它是你自己应该做的Javascript的基础知识)

答案 1 :(得分:0)

将您想要的分组的ID作为参数传递。然后你可以循环调用该函数。

function Add(ID) {
    var qty1 = document.getElementById('qty'+ID).value; 
    var u_price1 = document.getElementById('price'+ID).value; 
    ...
}