HelloWorld HelloWorld - 7 months ago 33
HTML Question

Adding dynamically text in JavaScript

hello everyone,

function changeIt()
{
var i = 1;
var j = 1;
my_div.innerHTML ="<br><br><input type='text' name='mytext' + i value='pleaseEnter malzeme' > <input type='text' name='mytet2'+j value='please quantity'> "
}

<input type="button" value="Add Ingredients" onClick="changeIt()">
<div id="my_div"></div>


i have these code piece to add textbox dynamically in my html file. Problem is that i can not reach text.

out.print(request.getParameter("mytext1")); doesnt work to reach mytext1 value.


how can i solve this problem? Thanks in advance.

Answer

Okay, first to get a reference of an element in JavaScript you need to call document.getElementById("my_div"). There is no such thing as automatic global scope population with IDs in JS.

Then your HTML string contains variables which are written as part of the string. Concatenation in JS works with the plus sign (+). So your string should be:

"<br><br><input type='text' name='mytext" + i + "' value='pleaseEnter malzeme'><input type='text' name='mytet2" + j + "' value='please quantity'>"

Everything assembled together:

<script type="text/javascript">
function changeIt() {
    var i = 1;
    var j = 1;
    document.getElementById("my_div").innerHTML = "<br><br><input type='text' name='mytext" + i + "' value='pleaseEnter malzeme'><input type='text' name='mytet2" + j + "' value='please quantity'>"
}
</script>

<input type="button"  value="Add Ingredients" onClick="changeIt()">
<div id="my_div"></div>

Regarding the print I have no idea what you're actually trying there...