YVS1102
YVS1102

Reputation: 2740

Change textfield attribute

I'm trying to change the textfield attribute.

My script is working fine.

But now I'm trying to change this part name='kadnya[]' to this name='kadnya['pudge']' or name='kadnya['drow']' depending on the table row. How can I achieve that?

Please check my script

$(document).ready(function() {
  $("#addRow").click(function() {
    $(".rowadded").append("<td></td>" +
      "<td><input type='text' class='kd' name='kadnya[]'></td>");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="POST">
  <table id="tablekd">
    <tr>
      <td>Pudge</td>
      <td class="rowadded"></td>
    </tr>
    <tr>
      <td>Drow</td>
      <td class="rowadded"></td>
    </tr>

  </table>
  <button type="button" id="addRow">Add</button>
</form>

Upvotes: 0

Views: 38

Answers (1)

mplungjan
mplungjan

Reputation: 178421

You need to use .each, then you can grab the index of the row you are adding to.

$(document).ready(function() {
  $("#addRow").click(function() {
    $(".rowadded").each(function(index,$row) {
      var name = $(this).prev().text(); // or $(this).parent().first().text();
      $(this).after("<td></td>" +
      "<td><input type='text' class='kd' name='kadnya["+name+"]'></td>");
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="POST">
  <table id="tablekd">
    <tr>
      <td>Pudge</td>
      <td class="rowadded"></td>
    </tr>
    <tr>
      <td>Drow</td>
      <td class="rowadded"></td>
    </tr>

  </table>
  <button type="button" id="addRow">Add</button>
</form>

Or

$(document).ready(function() {
  $("#addField").click(function() {
    $(".inputCell").each(function(index,$row) {
      var name = $(this).prev().text(); // or $(this).parent().first().text();
      $(this).append("<input type='text' class='kd' name='kadnya["+name+"]' />");
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="POST">
  <table id="tablekd">
    <tr>
      <td>Pudge</td>
      <td class="inputCell"></td>
    </tr>
    <tr>
      <td>Drow</td>
      <td class="inputCell"></td>
    </tr>

  </table>
  <button type="button" id="addField">Add input</button>
</form>

Upvotes: 1

Related Questions