fraktall
fraktall

Reputation: 32

JavaScript appendChild() input to form

I'm trying to add an <input> in <form> after page loads (<body onload="random()>"), but it is not working. What am I doing wrong?

This is the script it self:

function random()
{
    var points = Math.floor((Math.random() * 1000) + 1)
    var input = document.createElement("input");
    input.setAttribute("type", "hidden");
    input.setAttribute("name", "points");
    input.setAttribute("value", points.toString());
    document.getElementById("redeem_form").appendChild(input);
}

This is form:

<form action="/redeem" method="POST" id="redeem_form">
     <label for="user_email">Enter your email: </label>
     <input type="email" id="user_email" name="email" required>
     <input type="submit" value="Redeem">
</form>

Upvotes: 1

Views: 14438

Answers (2)

TryinHard
TryinHard

Reputation: 4118

Please note that the input added is actually hidden:

input.setAttribute("type", "hidden");

Please replace it with the;

input.setAttribute("type", "text");

Upvotes: 0

Andr&#233; Teixeira
Andr&#233; Teixeira

Reputation: 2562

You are actually creating a hidden input field. So, there is no error just an invisible field.

Try changing:

input.setAttribute("type", "hidden");

To:

input.setAttribute("type", "text");

Upvotes: 2

Related Questions