简体   繁体   中英

How to set name value of dynamic adding input ? javascript jquery

I have a web page for applying. In this web page, rows are dynamic add after addp button clicked.I can add new row successfully with addPf() method. And these input name attribute should be enName0, enName1, enName2....., but it works fail with name="enName"+aDWI.

Here is my html code:

<div>
<table>
 <tr>
  <td>
   <input type="button" id="addP" onclick="addPf()" value="addPeople">
  </td>
 </tr>
 <tr>
  <td>
   new row added in here;
  </td>
 </tr>
</table>
</div>

Here is my javascript code:

<script>

 var aDWI=0;
 function addPf()
 {
    newrow = '<tr><td><input style="width:98%" name="enName"+aDWI></td></tr>';
    $(newrow).insertAfter($('#staTable tr:eq('+aDWI+')'));
     aDWI = aDWI + 1;
  }
</script>

name="enName"+aDWI is not right.I have no idea about this, who can help me ?

Just update it with

<script>

 var aDWI=0;
 function addPf()
 {
    newrow = '<tr><td><input style="width:98%" name="enName'+aDWI+'"></td></tr>';
   $(newrow).insertAfter($('#staTable tr:eq('+aDWI+')'));
   aDWI = aDWI + 1;
}
</script>

Change from

newrow = '<tr><td><input style="width:98%" name="enName"+aDWI></td></tr>'; 

to

newrow = '<tr><td><input style="width:98%" name="enName'+aDWI+'"></td></tr>';

The issue is because you need to concatenate the variable in the string correctly, using the ' character.

Also note that you should really be using unobtrusive event handlers instead of the outdated on* event attributes. In addition, you can simplify the logic by using jQuery's append() , like this:

 var aDWI = 0; $('#addP').click(function() { newrow = '<tr><td><input style="width:98%" name="enName' + aDWI + '" value="' + aDWI + '"></td></tr>'; $('#staTable').append(newrow); aDWI = aDWI + 1; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <table id="staTable"> <tr> <td> <input type="button" id="addP" value="addPeople"> </td> </tr> <tr> <td> new row added in here; </td> </tr> </table> </div> 

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