George George - 5 months ago 10
jQuery Question

find element by object value inside data attribute

I have the following situation.
Have input, which has object in data attribute:

<input type='text' data-testname='{"repeat" : "{"group_id" : "1"}"}' value='value 1' />
<input type='text' data-testname='{"repeat" : "{"group_id" : "1"}"}' value='value 2' />
<input type='text' data-testname='{"repeat" : "{"group_id" : "1"}"}' value='value 3' />


Is there any selector, without loop, to find all element in document, without adding new data attribute (data-group_id = '1') where:

testname > repeat > group_id = 1

Answer

try something with filter()

<input type='text' data-testname='{"repeat" : {"group_id" : 1}}' value='value 1' /><input type='text' data-testname='{"repeat" : {"group_id" : 1}}' value='value 1' />
 var el =  $('[data-testname]').filter(function() {
  var data = $(this).attr('data-testname');
       if(JSON.parse(data).repeat.group_id  == 1)
             return this;
    });
console.log(el[0])

https://jsfiddle.net/enz70ud7/