在输入框中获取值的属性

时间:2013-10-15 07:39:52

标签: javascript

我正在编写一个程序,询问购买金额,然后计算折扣价。该函数有效,但属性innerHTML仅在我将其设置在段落p>中时才有效。我希望它在输入>中打印出来。所以我的问题是我需要使用什么属性。

错误讯息: 未捕获的TypeError:无法设置null

的属性'innerHTML'
<body>   
<p>Enter amount of purchases:<input type =" text" id ="purchase_amount" onkeyup ="calculate_discount()"/></p>
<p>Discount price:<input type="text" id =" discount_amount"/></p>
</body>

function calculate_discount() {
var purchase_amount = document.getElementById("purchase_amount").value;
var answer;
if (purchase_amount >= 10) 
{
    answer = purchase_amount - (purchase_amount * .10);
}
else if (purchase_amount < 10) 
{
    answer = purchase_amount;
}
document.getElementById("discount_amount").innerHTML = answer;

}

谢谢

http://jsfiddle.net/xK4s4/

2 个答案:

答案 0 :(得分:0)

Demo

输入元素不使用innerHTML属性,而是设置value属性。

document.getElementById("discount_amount").value = answer;

其他问题:

在小提琴中,运行代码onload,这意味着您的函数不在全局范围内,并且无法通过keyup事件调用。更改为no wrap - in head

您在discount_amount元素ID之前有一个空格:

<p>Discount price:<input type="text" id =" discount_amount"/></p>

答案 1 :(得分:0)

  1. 删除折扣金额输入元素

    的id属性中的空格
      

    id =“discount_amount”

  2.   
  3. 设置值而不是innerHTML。
  4.   
  5. 确保您的脚本放在输入元素之前。
  6.      工作脚本:

    <script>
        function calculate_discount() {
            var purchase_amount = document.getElementById("purchase_amount").value;
            var answer;
            if (purchase_amount >= 10) 
            {
                answer = purchase_amount - (purchase_amount * .10);
            }
            else if (purchase_amount < 10) 
            {
                answer = purchase_amount;
            }
            document.getElementById("discount_amount").value = answer;
        }
    </script>
    
    <body>   
      Enter amount of purchases:
      <input type="text" id="purchase_amount" onkeyup="calculate_discount()"/>
    
      Discount price:
      <input type="text" id="discount_amount"/>
    </body>
    

    Demo in jsfiddle.net