Home > other >  concatenate element name with attribute name in jquery selector
concatenate element name with attribute name in jquery selector

Time:12-27

I am trying to pass an attribute value to radio name in order to distinguish between different radio groups in my page:

$("input:radio[name=myRadio $(this).attr('data-id')]").change(function() {      
      //my code....
});

But i get some syntax error, please help with the correct syntax

CodePudding user response:

Your concatenation syntax is incorrect. It should look like this:

$('input:radio[name="myRadio'   $(this).data('id')   '"]').on('change', function() {      
  // your code...
});

Or in ES6:

$(`input:radio[name="myRadio${$(this).data('id')}"]`).on('change', function() {      
  // your code...
});

Better yet, don't build selectors at runtime. Use common classes to group elements by structure, along with DOM traversal methods to relate them to each other when events occur.

  • Related