简体   繁体   中英

How can I access form input from an input field which was created dynamically via a Javascript function?

I'm new to programming and hope you can help me out with this little number comparison game that I'm trying to build.

I have two functions. The first function creates the playing field in HTML via a button press. One of the elements created on the playing field is an input field where the player can enter their guess. In the second function I compare two numbers - the one that was generated randomly and the one that was input by the player. Unfortunately I can't access the number which was entered by the player.

Maybe someone has got an idea. Thank you very much.

This is what the functions look like:

function startGame(){
(...)
    const inputField = document.createElement("input");
    inputField.setAttribute("type", "number");
    inputField.setAttribute("id", "guess");

    document.getElementById("guess").appendChild(inputField);
}
function compareInput(){
    let inputValue = document.getElementById("guess").value;
(...)
}

I implemented a proof-of-concept, which probably differs from your requirements, but it should help you finding the right path. First, let's make sure that the new field has a value. Next, make sure that we append it to document rather than itself.

 function startGame(){ const inputField = document.createElement("input"); inputField.setAttribute("type", "number"); inputField.setAttribute("id", "guess"); inputField.value = parseInt(Math.random() * 10) + 1; document.body.appendChild(inputField); } function compareInput(){ let inputValue = document.getElementById("guess").value; console.log(inputValue); } startGame(); compareInput();

  1. You're trying to append "guess" to itself. That doesn't work like that. Try to append it to another div or body.

  2. You have two elements with the same ID. The first is the wrapper and the second is the input. Hence ur function compareInput() is trying to get the value of the wrapper.

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