简体   繁体   中英

How to add javascript value to an existing value of textbox

i want to generate a 6 digits and add them to an existing text such as :

this java script

<script>
function myFunction() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("demo").innerHTML = x;
}</script>

it's output is random number ..

i want to add it to the text below in value

<input class="textbox"type="text" value="My Age is [ Here is The Output of the JavaScript] , am i old ?" >

is it possible ?

You need to replace document.getElementById("demo").value= x; to document.getElementById("demo").value= "My Age is " + x + ", am i old ?";

Here you can find a jsfiddle to see your code: https://jsfiddle.net/80rcowh3/3/

Basically I've added the id "demo" to your input. This is mandatory if you want to target the element using the function getElementById .

Than I've created the code to add your random number in the middle of the old text. At the end I put the new text in the input. You'll find comments on the code.

I hope it helps :-)

<script>
function myFunction() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("demo").innerHTML = "My Age is ["+x+"] , am i old ?";
}
</script>

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