简体   繁体   中英

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.

尝试将您的 innerHTML 更改为:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM