JQuery/Ajax function not working for a new row generated

I'm trying to implement a function for a dinamic table, the table starts like this:

<table>
    <thead><tr><th>Código</th><th>Nombre</th><th>Cantidad</th><th>Precio</th></tr></thead>
    <tbody id="bodyVender">
        <tr>
            <td><input id="inp0" type="text" autofocus="true" class="form-control"></td> <td id="tdN0"></td> <td><input id="tdC0" type="text" class="form-control"></td> <td id="tdP0"></td>
        </tr>
    </tbody>
</table>

And then i'm adding more table rows to the tbody when the JQuery function is called, like this:

$('#bodyVender').append('<tr><td><input id="inp'+count+'" type="text" class="form-control"></td> <td id="tdN'+count+'"></td> <td><input id="tdC'+count+'" type="text" class="form-control"></td> <td id="tdP'+count+'"></td></tr>');

As you can see, the new row created will have tds and inputs with a new ID determined by the "count" variable, so that input ID could look like: inp0 , inp1, inp2 after each function call.

This works, but just the first time, even when I'm calling the function for that new created ID.

I'm using $(document).on to call the function, and I think that should work for the new row created.

Here's the entire code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Panel de Administración</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="estilo3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(Principal);

  function Principal(){
  var count = 0;                                                //sell's counter

  $(document).on('keydown','#inp'+String(count), function(e){  //when press key on input with id="inp0"
    if(event.keyCode == 13){                                  //if the key pressed is Enter
      VenderConsulta($(this).val(),count);                   //call function VenderConsulta with the typed code
      }
    });

  function VenderConsulta(Codigo,ntd){
    datos={codigo:Codigo};              // the code to send
    $.ajax({
      url:"bringMeTheData.php",
      type: "POST",
      data: datos,
      success: function(datos){
        console.log(datos);               //i'm recibing something like [{"Nombre":"A product name","P_venta":"990"}]
        count+=1;                         //next time i'll choose the new input with id="inp1"
        $(':focus').blur();               //blur the input
        var arr = JSON.parse(datos);
        var tdNombre = arr[0].Nombre;
        var tdPrecio = arr[0].P_venta;
        $('#tdN'+ntd+'').html(tdNombre);
        $('#tdC'+ntd+'').val(1);
        $('#tdP'+ntd+'').html(tdPrecio);

        $('#bodyVender').append('<tr><td><input id="inp'+count+'" type="text" class="form-control"></td> <td id="tdN'+count+'"></td> <td><input id="tdC'+count+'" type="text" class="form-control"></td> <td id="tdP'+count+'"></td></tr>');

        $('#inp'+count).focus();  //setting focus to the new created input
      }
    });
  }
 }

</script>
</head>

<body>
<div class="container-fluid">
  <section class="tablaVender">
    <div class="row">
      <div class="table-responsive" style="background:white">
        <h3 style="margin-left:15px"> Venta de productos </h3>
        <table class='table table-hover table-bordered'>
          <thead><tr><th>Código</th><th>Nombre</th><th>Cantidad</th><th>Precio</th></tr></thead>
          <tbody id="bodyVender">
            <tr>    <!-- This is the input and i'll add more trs like this in the function VenderConsulta -->
              <td><input id="inp0" type="text" autofocus="true" class="form-control"></td> <td id="tdN0"></td> <td><input id="tdC0" type="text" class="form-control"></td> <td id="tdP0"></td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </section>
</div>

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>

Why this works just the first time and then no more? I'm working wrongly with that new row created? Sorry for my bad english and thanks.

Upvotes: 0

Views: 79

Answers (2)

BurningLights
BurningLights

Reputation: 2397

Your selector for the keydown function will only trigger it for the first input. You only call .on() once, and you give it '#inp'+String(count) as the selector. Your variable count is 0 at that point, so it will only work with the input that has the id inp0. You could fix this by using a selector that will work with all input[x] ids. And attribute selector that checks the beginning of the id would work. Like:

  $(document).on('keydown','[id^=inp]'function(e){  //when press key on input with id="inp0"
    if(event.keyCode == 13){                                  //if the key pressed is Enter
      VenderConsulta($(this).val(),count);                   //call function VenderConsulta with the typed code
      }
    });

Upvotes: 1

bzrk
bzrk

Reputation: 105

It's because this code:

$(document).on('keydown','#inp'+String(count), function(e){  //when press key on input with id="inp0"
    if(event.keyCode == 13){                                  //if the key pressed is Enter
        VenderConsulta($(this).val(),count);                   //call function VenderConsulta with the typed code
    }
});

will only get executed once, and when it does, the value of count is 0. So you're only binding the event to the first element.

Instead, you should probably use a class to target those elements.

Upvotes: 1

Related Questions