Reputation: 1421
Title says it all, i am setting a value in a variable in a javascript. I want to set that value as value of the one of the row in my form.
here is the code, this is based on previous similar questions and their accepted answers, but somehow it does not work for me.
<html>
<head>
<script>
var counter = 0;
var limit = 50;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Element " + (counter + 1) + " <input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
</head>
<body>
<form method="POST" align="center">
<script>
var emotion = "";
var raw = Math.random();
var final = Math.ceil(raw * 4);
if (final == 1)
document.getElementById("someid").value = "A";
else if (final == 2)
document.getElementById("someid").value = "B";
else if (final == 3)
document.getElementById("someid").value = "C";
else if (final == 4)
document.getElementById("someid").value = "D";
</script>
<div id="dynamicInput">
Title<br><input type="text" value="" name="myInputs[]" id="someid" disabled>
</div>
<input type="button" value="Add another event" onClick="addInput('dynamicInput');">
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
I also tried something like:
document.forms[0].myInputs[0].value="Whatever"
inside the script tags, but that also does not work.
Edit_1 I expect some value in the disabled input field, just below the title, but its empty.
Here is the image:
How can I have some value based on a random number generator there?
Upvotes: 0
Views: 2306
Reputation: 2333
check the jsfiddle, this is due to how u arrange ur script, you either move ur code below the html, or use onload() event
example
onload="test()"
then you will no need to worry where the js should put
<script>
function test(){
var emotion = "";
var raw = Math.random();
var final = Math.ceil(raw * 4);
if (final == 1)
document.getElementById("someid").value = "A";
else if (final == 2)
document.getElementById("someid").value = "B";
else if (final == 3)
document.getElementById("someid").value = "C";
else if (final == 4)
document.getElementById("someid").value = "D";
}
</script>
https://jsfiddle.net/gw04jhoj/
you can refer to this for more info Javascript that executes after page load
Upvotes: 2
Reputation: 1797
Your script is running before those HTML elements have been created, and so setting their value will fail, as document.getElementById("someid") doesn't exist yet. You should see this fail in the error console in the browser (F12).
Try moving the script until after you've created the HTML elements in question, or better yet change your script to only execute once the document has loaded.
Upvotes: 1
Reputation: 3844
You should use :
document.getElementById("someid").value="whatever";
Upvotes: 0