I got an error when using double quotes in input value

in my template, there is a code that outputs variations selector. Page crashes when a user enters variation like 10″ x 15″.

I see that problem is in this part of code value=”‘ + variant.options[i] +'” I tried using replace() for removing double quotes and it’s ok. But I want to show double-quotes. How to avoid the error without trimming double quotes?

if (variant) {
  var form = jQuery('#' + selector.domIdPrefix).closest('form');
  for (var i = 0, length = variant.options.length; i < length; i++) {

    var radioButton = form.find('.swatch[data-option-index="' + i + '"] :radio[value="' + variant.options[i] + '"]');
    if (radioButton.length) {
      radioButton.get(0).checked = true;
    }
  }
}

Answer

You can use CSS.escape and template literals

if (variant) {
  var form = jQuery('#' + selector.domIdPrefix).closest('form');
  variant.options.forEach((opt,i) => {
    const radioButton = form
      .find(`.swatch[data-option-index=${i}] :radio[value="${CSS.escape(opt)}"]`);
    if (radioButton.length) {
      radioButton.eq(0).prop("checked",true);
    }
  })
}

Leave a Reply

Your email address will not be published. Required fields are marked *