简体   繁体   中英

Output javascript value in a text input

I'm not very good in javascript. I have coded this 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);
}

I am outputting it inside an input field when the page loads:

<body onload='calculateTotal()'>
    <input type="text" required="required" name="total" class="text" id="totalPrice"/>
</body>

The problem is that the value is not displayed in the input field when the page loads. When I try the same javascript with a div, it works. I want to make the value to be outputted in the input field because the value is still needed for user manipulation. Kindly check and help me on how to do it.

You're looking for .value

divobj.value = cakePrice;

More generally:

// 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;
}

Working Fiddle

很简单,您已经将元素以及要显示的值存储在变量中:

divobj.value = cakePrice;

Try do to this:

<input type="text" id="totalPrice" />

JS:

$().ready(function(){
    var total = 4 + ( 5 + 7 + 9 + 2 ) * ( 8 * 3 );
    $('#totalPrice').val(total);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM