从表中的td获取表单中的输入值

时间:2014-03-12 14:40:39

标签: javascript html

当用户将值输入到仅包含数字的文本框中时,我需要执行所有这些功能。当值不是数字时,我还想在目标文本框中显示一条消息,请求它们插入有效值。当输入数据正确时,我希望函数对这些值进行计算并将其显示在目标td中。此外,当没有插入值时,我希望td显示0€。我尝试过使用inner.HTML方法。

我知道我需要触发一个事件到函数,但我不确定哪个是最好的方法。

我也怀疑是否能像我一样编写HTML标记,在td标记内插入输入标记。

鉴于标记是合法的,我需要帮助编写第一个函数并使其工作。所有其他功能都已注释掉。

以下是Fiddle的链接:http://jsfiddle.net/MMendes/mqu7A/

   var A = {

       //calculate the total invoiced for the day
       calcTotalDay: function () {
           //get the total invoiced for the day and set the value to 0€
           var dayTotal = document.getElementById("daytotal");
           dayTotal.innerHTML = "0€";
           //get the input values for invoiced and lastInvoiced
           var invoiced = document.getElementById("invoiced").value;
           var lastInvoiced = document.getElementById("lastinvoiced").value;
           //make sure the input values are number types. If not display 
           //message demanding to insert a valid value
           if (typeof invoiced !== Number)
               invoiced.innerHTML = "Insert a valid value!";
           if (typeof lastInvoiced !== Number)
               lastInvoiced.innerHTML = "Insert a valid value";
           //return the sum of the total by adding invoiced 
           //and lastInvoiced and adding the euro sign
           return invoiced + lastInvoiced + " €";
       }

   };

1 个答案:

答案 0 :(得分:0)

由于你的小提琴没有calcTotalDay功能,我会做出我认为正确的假设:

var A = {

   //calculate the total invoiced for the day
   calcTotalDay: function () {

       //get the total invoiced for the day and set the value to 0€
       var dayTotal = document.getElementById("daytotal");
       dayTotal.innerHTML = "0€";

       //get the input values for invoiced and lastInvoiced ""parsed as integers""
       var invoiced = parseInt(document.getElementById("invoiced").value, 10);
       var lastInvoiced = parseInt(document.getElementById("lastinvoiced").value, 10);

       //make sure the input values are number types. If not display 
       //message demanding to insert a valid value
       var type1 = typeof invoiced;
       var type2 = typeof lastInvoiced;
       if (type1 !== 'number')
           invoiced.innerHTML = "Insert a valid value!";
       if (type2 !== 'number')
           lastInvoiced.innerHTML = "Insert a valid value";

       //return the sum of the total by adding invoiced  
       //and lastInvoiced and adding the euro sign ""only when both are numbers""
       if(type1 === 'number' && type2 === 'number')
           return invoiced + lastInvoiced + " €";
       else 
           return "invalid";
   }

};