0

I'm trying to get the id of a div element that I show from the database. The ID is generated dynamically, and it corresponds whit the record id, but when I try to get the id through a click event, I get only the id of the first element, or in other cases, all the ID's of the dynamic fields.

Here is the code fragment of my .js file:

        /* Every field element is dynamically generated */
        $('#data .fields[id^=field_]').click(async() => {
            $('form').attr("action", "http://xx.xx.7.205:3000/api/pedidos/modificar");
            const id = $(this).attr('id').slice('-')[1];
            const ret = new Buscar();
            const json = ret.buscar(id);
            llenarCamposFormulario(id, json);
            $('.anular').click(async() => {
                const ret2 = new eliminarPedido();
                const what = await ret2.buscar(id);
                console.log(what);
                resetFields();
            });
        });

Thanks in advance!

Jean Louis
  • 15
  • 5

1 Answers1

1

If your divs are dynamically generated, you should change your handler to handle click on current and future content.

$('#data').on('click', '.fields[id^=field_]', function() {/* on click open form */} )

$('#data').on('click', '.fields[id^=field_] .anular ', function() {/* on click cancel operation */} )

In the anular operation, just recompute ids and stuff instead of reusing it from the open form handler.

By this way, you catch all clicks on #data, and the handler is called only of the clicked element matches the selector in the second parameter. In the previous way, you add handler to every existing div, and the later divs are not there at this moment.

That should do the trick ! Happy coding

djleop
  • 687
  • 4
  • 18
  • Hey thanks! I will try immediately to come an check the answer! Edit: I have forgotten that my button is outside the form I hope this work anyway – Jean Louis Jun 03 '20 at 23:21
  • If your button is outside the form and not added dynamically, the original code is not correct since it adds a handler to the button for each field. You may want this button to work independently of a field. – djleop Jun 04 '20 at 06:16