akabaka
akabaka

Reputation: 115

how to make a function that bind a button to the same function

see jsfiddle

I'm reposting this because I may have not described this correctly. I'm trying to add a button to a table within a form that create a new row for input, and at the end of the new row, it should display another button to insert another line, and so on.

I try to achieve this by calling the function from itself to add the new button when the line is created and hide the previous one.

Here's my actual code

  if(!$('input[name="addressee\\[line3\\]"').length) {
    add_button(3);
  } else if (!$('input[name="addressee\\[line4\\]"').length) {
    add_button(4);
  }

  function add_button(number) {
    let btn = $('<input/>', {
      'type': 'button',
      'value': 'add line',
      'data-number': number,
      'on': {
        click: function() {
          let row  = $('<tr><td><label for="line' + number + '">Addresse(suite)</label></td><td><input name="line' + number + '" style="width: 300px"/></td></tr>');
          $('input[name="addressee\\[line' + (number - 1) + '\\]"').closest('tr').after(row);
          if ($(this).data('number') == '3') {
            add_button(4);
          }
          $(this).hide();
        }
      }
    });
    $('input[name="addressee\\[line' + (number - 1) + '\\]"').after(btn);
  }

and here is the HTML, it's just a simple table

<table>
    <tr>
      <td>
        <label for="line2">Adresse</label>
      </td>
     <td>
       <input type="text" name="addressee[line2]" value="250 rue des granges" style="width: 300px"><br>          
     </td>
    </tr>
</table>

It create the first line, but the button is not showing on the second when it's created.

see jsfiddle

I've tried many things, but it's the best I've managed to get.

Upvotes: 0

Views: 121

Answers (1)

Alexis
Alexis

Reputation: 1784

Be careful on your add_button fonction, when you set your next functions when button is clicked

function add_button(number) {
  let btn = $('<input/>', {
    'type': 'button',
    'value': 'add line',
    'data-number': number,
    'on': {
      click: function() {

        // \/ HERE YOU DON'T SET "addressee[line..]" BUT JUST "line" ON THE NAME OF THE INPUT

        let row  = $('<tr><td><label for="line' + number + '">Addresse(suite)</label></td><td><input name="line' + number + '" style="width: 300px"/></td></tr>');

        // /\

        $('input[name="addressee\\[line' + (number - 1) + '\\]"').closest('tr').after(row);
        if ($(this).data('number') == '3') {
          add_button(4);
        }
        $(this).hide();
      }
    }
  });
  $('input[name="addressee\\[line' + (number - 1) + '\\]"').after(btn);
}

Upvotes: 1

Related Questions