Home > Net >  how to pass value inside loop in template to jquery
how to pass value inside loop in template to jquery

Time:10-09

I want to pass a value inside a loop into a query. I made a list of rings and displayed those using a loop in a twig. and I wanted to edit one of them when I clicked the Anker.

This is my twig,

        {% set ring_id = ''%}
        {% for ring in rings%}
        <tr>
            <td><p>{{ ring.id }}</p></td>
            <td><p>{{ ring.ring_name }}</p></td>
            <td><p>{{ ring.ring_type }}</p></td>
            <td><p>{{ ring.ring_shape }}</p></td>
            <td><p>{{ ring.size }}</p></td>
            <td><p>{{ ring.price }}</p></td>
            {%set ring_id = ring.id %}
            
            <td><a href="#" id='ring_delete' >Delete</a></td>
            
        </tr>
        {% endfor %}

This is my query,

  <script>

$(function() {
    var ring_id = "{{ring_id}}";
    $('#ring_delete').on('click', function(e) {
     $.ajax({
            url: "{{ url('admin_product_custom_delete_ring') }}",
            type: "POST",
            dataType: 'json',
            data: { 
            },
            async: false
        }).done(function(data){
            alert('check'   data);
        }).fail(function(){
            alert("no");
        })

    });
 </script>

So I want to delete the ring that I chose by passing ring_id to the url. However, it says ring_id does not exist, even though I added {%set ring_id %}. How can I pass a value inside a loop using a twig into a jquery?

CodePudding user response:

Try using data attributes.

<a href="#"  data-id="{{ ring.id }}">Delete</a>
$('.ring_delete').on('click', function(e) {
  var ring_id = $(this).data('id');

Also notice I changed ring_delete from an id to a class. This is because ids need to be unique and there can only be one with that name. Since it's inside a loop and will be several, we should use classes instead to reference.

  • Related