-1

I want jQuery to do a (simulated) click on a radio button inside an LI with a data attribute named product. Below code is not doing the trick. Any help would be appreciated.

var clicky = 1234;
var selector = 'li[data-product="' + clicky + '"].radio';

jQuery(selector).trigger('click');
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Kurdt94
  • 95
  • 2
  • 12
  • If it is dynamic element use `delegate` `event` binding. – Parth Trivedi Jan 12 '16 at 12:43
  • Possible duplicate of [Selecting element by data attribute](http://stackoverflow.com/questions/2487747/selecting-element-by-data-attribute) – Amar Singh Jan 12 '16 at 12:43
  • 2
    What you have should work, assuming the element exists in the DOM. Do you have a specific problem with the code? Seeing your HTML may help us find an issue. – Rory McCrossan Jan 12 '16 at 12:43
  • Your description indicates a hierarchy, but your selector assume the `data-product`, and the `.radio` class are both on the `LI` element. Try using descendant selectors as per example below, and please *please* post your HTML when asking a question like this :) – iCollect.it Ltd Jan 12 '16 at 12:51

1 Answers1

0

You need to show the actual HTML as things can vary slightly based on the DOM, but all your selectors are operating on the same element, not on an element and its descendants. Simply adding a space between selectors makes them descendant selectors.

Try something like:

var clicky = 1234;
var selector = 'li[data-product="'+clicky+'"] .radio';

jQuery(selector)[0].click();  // Trigger native click event

or

jQuery(selector).click();  // Trigger jQuery click event

Basically you are missing a space before the .radio. Currently you are trying to click the LI instead on the descendant.

or possibly

var selector = 'li [data-product="'+clicky+'"].radio';

if the button has the data (missing space after LI).

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202