0

I have a dynamic table where a button on click adds a new row. I want to add a name attribute each time new row created.

Here's my code:

$(function() {
  const $tb = $('#service-table tbody');
  $("tr",$tb).eq(0).hide();
  $("#serviceAdd").on("click",function() {
    const $row = $tb.find("tr").eq(0).clone();
    $row.show();
    $row.find("select").val("").attr("name", "service_id[]"); // reset the select
    $row.find(".s_qty").val().attr("name", "s_qty[]"); // reset the numbers
    $row.find(".s_total").val().attr("name", "s_total[]"); // reset the numbers     
    $tb.append($row);

  });
});

It shows error Uncaught TypeError: $row.find(...).val(...).attr is not a function

I have tried with many changes but it shows the same error.

How can I add attribute to new rows?

Nathaniel Flick
  • 2,902
  • 2
  • 22
  • 31
Farlar
  • 47
  • 5
  • `).val().` *gets* the value, so it will likely be a string, which doesn't have a `setAttribute` method. Having said that, `.setAttribute()` is also not a jquery function, so it's probably the line before that one. Use `$(..).val("").attr("name", "...")` – freedomn-m Oct 31 '22 at 17:47
  • 1
    Does this answer your question: [Setting attribute in jQuery](https://stackoverflow.com/questions/5995628/adding-attribute-in-jquery/5995650#5995650) – freedomn-m Oct 31 '22 at 17:50
  • Same thing. I have updated the question with attr(). Can you please tell me for my case, which way I can add attribute? – Farlar Oct 31 '22 at 17:55
  • Debug the value of `$row.find(".s_qty").val()` – freedomn-m Oct 31 '22 at 17:57
  • Example here for changing an attribute: https://api.jquery.com/attr/#attr-attributeName-value – Nathaniel Flick Oct 31 '22 at 17:58
  • Solved it. I call each line again without val(). – Farlar Oct 31 '22 at 18:17
  • 1
    If you want to reset the value, use `.val('')` like you did in the `select` line. – Barmar Oct 31 '22 at 18:19

0 Answers0