Pick id dynamic value - Jquery

Asked

Viewed 31 times

0

I am using PHP with AJAX. I need to take a multiple Forms id and run a function in AJAX. I am passing the ids of the Forms like this :

<form id="formItem<?= $idItem ?>">

However, in Jquery I cannot get the id, each form has a different id. All on the same page. My AJAX:

$('#formItem').submit(function(e){
    e.preventDefault();

    var idProduto = $('#idProduto').val();
    var precoProduto = $('#precoProduto').val();
    var qtdeCompra = $('#qtdeCompra').val();

    $.ajax({
        url: 'http://localhost/fcgeti_bairrojuventude/loja2/inserir.php',
        method: 'POST',
        data: {idProd: idProduto, precoProd: precoProduto, qtdeProd: qtdeCompra},
        dataType: 'json'
    });
    getItens();       

});

If you can help me. I’ve tried concatenating but it didn’t work.

Thank you

  • qnd I can’t get id of any element I try to do this before submitting the ajax request, to debug and check any error with the browser console opened to display any error and already inside the javascript code placed: `Alert( $('#id_que_eu_quer0').val()+'/ '+ $('#id_seguinte').val()); // if there is an error you will see in the console if any element is returning Undefined or another value....

1 answer

0

The problem there is related to the manipulation of the DOM; remember that the Id of an element can never repeat; so in that situation you can work with the classes to identify the elements. I made an example below without having to mix PHP inside the script, I hope it helps:

$('.form').submit(function(e){
    e.preventDefault();
    
    //pega o id do formulário
    var formId = $(this).attr('id');
    
    //pega todos os seus valores (e nomes dos campos) POST de uma vez
    var str = $(this).serialize();
    
    $('#consoleLog').html('formulário:'+formId+'<br />Data:'+str);
    
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form" id="1">
  <input type="text" name="i1" value="v1" />
  <button type="submit">Enviar form 1</button>
 </form>
 <br />
 <form class="form" id="2">
 <input type="text" name="i2" value="v2" />
  <button type="submit">Enviar form 2</button>
 </form>
 <br />
 <form class="form" id="3">
  <input type="text" name="i3" value="v3" />
  <button type="submit">Enviar form 3</button>
 </form>
 
 <p id="consoleLog"></p>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.