Using if in jquery and twig

I want to check if id is equal to <li>contact id or not, my jquery code is below:

var points = new Array();
var i = 0;

$(this).toggleClass('selected');
$('#result').html($('#firstList .selected').clone());

$id = $(this).attr('id');
{% for contact in contacts %}
    $idd = "{{ contact.id }}";
    if ($id === $idd){
        points[i] = "{{ contact.gsmPrimary}}";
        i++;
        $('#result').val(points.join(';'));
    }
{% endfor %}

First I get ideach select element li, and then I have a contact object, I want to check if the id of the selected <li>contact is equal to .id or not, if it is equal I will add contact.gsmprimaryin textareawith the name result

thanks for the help

+4
source share
1 answer

First of all, separate JS script and twig template data. Just take all contacts into one JS variable and use this variable for processing in javascript

var contacts_json = $.parseJSON("{{ contacts|json_encode() }}"); 

var points = [];

$(this).toggleClass('selected');

$('#result').html($('#firstList .selected').clone());

$id = $(this).attr('id');

for(var i in contacts_json){

  if($id == contacts_json[i]['id']){

    points[] = contacts_json[i]['gsmPrimary'];
  }

}
$('#result').val(points.join(';'));
+3
source

Source: https://habr.com/ru/post/1616562/


All Articles