HelloWorld
HelloWorld

Reputation: 39

Adding dynamically text in JavaScript

Javascript:

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'> "
}

HTML:

<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 cannot reach text.

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

How can I solve this problem? Thanks in advance.

Upvotes: 1

Views: 9810

Answers (2)

Hugo G
Hugo G

Reputation: 16494

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...

Upvotes: 1

zack.lore
zack.lore

Reputation: 527

Try changing your innerHTML to this:

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

Upvotes: 1

Related Questions