我在javascript方面不是很好。我编写了这个javascript:
function calculateTotal()
{
var cakePrice = 4 + ( 5 + 7 + 9 + 2 ) * ( 8 * 3 );
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = cakePrice;
$('add').val(divobj);
}
我在页面加载时在输入字段中输出它:
<body onload='calculateTotal()'>
<input type="text" required="required" name="total" class="text" id="totalPrice"/>
</body>
问题是页面加载时输入字段中不显示该值。当我尝试与div相同的JavaScript时,它的工作原理。我想在输入字段中输出值,因为用户操作仍然需要该值。请检查并帮助我了解如何操作。
答案 0 :(得分:1)
您正在寻找.value
divobj.value = cakePrice;
更一般地说:
// the selector is here for caching, so the browser doesn't have to look for it every time
// Make sure you put your code in the bottom of the body section, or inside a ready handler
var divobj = document.getElementById('totalPrice');
function calculateTotal(){
var cakePrice = 4 + ( 5 + 7 + 9 + 2 ) * ( 8 * 3 );
divobj.style.display='block';
divobj.value = cakePrice;
}
答案 1 :(得分:0)
很简单,您已经将元素存储在变量中,以及要显示的值:
divobj.value = cakePrice;
答案 2 :(得分:-1)
尝试这样做:
<input type="text" id="totalPrice" />
JS:
$().ready(function(){
var total = 4 + ( 5 + 7 + 9 + 2 ) * ( 8 * 3 );
$('#totalPrice').val(total);
});