jquery get text from dynamically created input

Viewed 133

I have some code that displays the JSON and allows the user to edit the text. After editing, I want to allow the user to click a button to save the new input value. Everything works as expected except for grabbing that new input value.

for (let i = 0; i < jsonObject.results.length; i++) {
    var row = `<tr scope="row" class="test-row-${jsonObject.results[i].id}">
    <td id="fName-${jsonObject.results[i].id}" data-testid="${jsonObject.results[i].id}">${jsonObject.results[i].firstName}</td>
    // some code

    $(`#save-${jsonObject.results[i].id}`).click(function(){
      clickAButton(jsonObject.results[i].id, jsonObject, i);
    });

    $(`#fName-${jsonObject.results[i].id}`).on('click', editResult)
    
}
function editResult(){
  var testid = $(this).data('testid')
  var value = $(this).html()

  $(this).unbind()
  $(this).html(`<input class="result form-control" data-testid="${testid}" type="text" value="${value}">`)
}
function clickAButton() {
  var text = $(`#fName-${jsonObject.results[index].id}`).val();
  console.log("text from " + text);
  // code
}

the code above displays

text from

How do I get it to display the new user input?

1 Answers

Instead of writing mutliple event handler for all tds and button you can use only one event handler for button and td . So, when td is clicked just remove data-testid attribute from td so that again that event will not get called and to get input value use $(this).closest('tr').find('.result').val() this will give you input value where save button is clicked.

Demo Code :

var jsonObject = {
  "results": [{
    "id": 1,
    "firstName": "sas"
  }, {
    "id": 2,
    "firstName": "cd"
  }]
}

for (let i = 0; i < jsonObject.results.length; i++) {
  var row = `<tr scope="row" class="test-row-${jsonObject.results[i].id}">
    <td id="fName-${jsonObject.results[i].id}" data-testid="${jsonObject.results[i].id}">${jsonObject.results[i].firstName}</td><td><input type='button' id='save-${jsonObject.results[i].id}' value ='save'></td></tr>`

  $("table").append(row)
}

$(document).on('click', 'td[data-testid]', function() {
  var testid = $(this).data('testid')
  var value = $(this).html()
  $(this).html(`<input class="result form-control" data-testid = "${testid}" type = "text"
  value = "${value}" >`)
  //removed data-testid
  $(this).removeAttr("data-testid");
})

$(document).on('click', '[id*=save-]', function() {
  //use class to find input
  var text = $(this).closest('tr').find('.result').val();
  console.log("text from " + text);

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
</table>

Related