Needed to double-click the button to add input dynamically with jquery

1

I have the following script:

$(document).ready(function() {
    var i = 0;
    $("#add_row").click(function() {
        if(i <= 5)
        {
            $('#addr' + i).html("<div><input type='text' name='cirurgia' value="+i+"></div>");
            $('#input').append('<div id="addr' + (i + 1) + '">');
            i++;
        }   
    });

    $("#delete_row").click(function() 
    {
        if (i > 1) 
        {
            $("#addr" + (i - 1)).html('');
            i--;
        }
    });
});

When the user clicks the <div id="add_row"> , the script adds an input and if the user clicks the <div id="delete_row"> , deletes the last added input.

So far the script is working correctly, however it happens that to add the 1st input the user needs to click twice on the "add_row" button. Then to add the 2nd, 3rd, 4th and 5th% with% is just click once even normally. Why does this happen?

Simple HTML:

<input type="button" id="delete_row" value="deletar">
<input type="button" id="add_row" value="adicionar">
<br>
<div id="input">
</div>
    
asked by anonymous 23.11.2017 / 02:33

1 answer

2

The problem lies in this line:

$('#addr' + i).html("<div><input type='text' name='cirurgia' value="+i+"></div>");

To solve this you can reverse the order of the instructions and adjust to #addr0 so that the first visible element is html :

$('#input').append('<div id="addr' + (i+1) + '">');
$('#addr' + (i+1)).html("<div><input type='text' name='cirurgia' value="+(i+1)+"></div>");

It's even easier to add the html you want in i+1 , without having to do the following steps:

i++;
$('#input').append('
      <div id="addr${i}" class="addr">
          <div><input type='text' name='cirurgia' value="${i}"/></div>
      </div>');

Here I used template literals to facilitate the interpolation of 1 in the middle of the text, as well as being able to separate into several lines, indenting the generated html.

Note that I have also added a class append to i master to help with removal, which should be:

$(".addr").last().remove();
i--;

Example to work:

$(document).ready(function() {
  var i = 0;
  $("#add_row").click(function() {
      if(i <= 5)
      {
          i++;
          $('#input').append('
          <div id="addr${i}" class="addr">
              <div><input type='text' name='cirurgia' value="${i}"/></div>
          </div>');
      }   
  });

  $("#delete_row").click(function() 
  {
      if (i >= 1) 
      {
          $(".addr").last().remove();
          i--;
      }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="input"></div>

<button id="add_row">Add Row</button>
<button id="delete_row">Delete Row</button>
    
23.11.2017 / 03:10