Using a variable in a form field

Viewed 145

I am trying to pre-fill a form with the content of a variable. HTML with node.js javascript. I feel like this should be easier than it is ... in fact I can't find any way to do this at all.

This is my javascript code to obtain the variable value:

const urlParams = new URLSearchParams(location.search);
for (var entry of urlParams) { 
    var URLentry = entry[0];
};   
if (!URLentry) { URLentry = "TESTING" };
$("#URLentry").text(URLentry);

and this is my form in the html file:

    <form id='join-game-form'>
            <div class='form-game'>    
              <input type='text' class='form-control' id='gameId' aria-describedby='Game Code' value = `${URLentry}`> 
              <small class='form-text text-muted'><span id='game-error'></span></small>
            </div>
            <button type='submit' class='btn btn-primary' href='#' role='button'>Start Game</button>
        </form>

the bit in the form value = ${URLentry} just treats it as text, the variable does not pass in. Any ideas? Is it possible to use variables in forms?

1 Answers

try this:

document.querySelector("#gameId").value = URLentry;

value = ${URLentry} is not working because its HTML, you dont have access to your variables in your HTML file.

You could generate your HTML text in the JS file and than add it to your document like this:

let myVar = "Hello world";
let html =`<div>${myVar}<\div>`;

document.body.innerHTML += html;
Related