Ad

Add Class To Checked = True Input

- 1 answer

So I have a drop-down selection of a product. And I just want to be able to add a class when the input is checked. I know that with css you can recognize the input:checked but I need an extra for further development. This is part of my code

for (var i=0,length=variant.options.length; i<length; i++) {
    var radioButton = $productForm.find('.swatch[data-option-index="' + escape(i) + '"] :radio[value="' + variant.options[i].replace(/\"/g,'\\"') +'"]');
    if (radioButton.length) {
      radioButton.get(0).checked = true;
    }
  }

And I tried to add the class in this way:

if (radioButton.length) {
      radioButton.get(0).checked = true.addClass("selected");;
}

And in this way

if (radioButton.length) {
      radioButton.get(0).checked = true;
      radioButton.get(0).addClass("selected");
}

Neither of this ways work, I can't understand why.

Ad

Answer

They don't work as you're mixing javascript and jquery - yes jquery is javascript, but it has its own methods that apply to jquery objects, one of which is .addClass().

So this code:

var radioButton = $productForm.find(...

returns a jquery object, while:

radioButton.get(0)

gives the original DOM object, which does not have an .addClass() method.

You can use .addClass without using .get(0) as in:

radioButton.addClass("selected");
Ad
source: stackoverflow.com
Ad