Parse value of option into html attribute

故事扮演 提交于 2019-12-04 19:22:22

To just set the data-selly-product attribute of the button you have to use the .dataset property. Quoting from the link:

The name of a custom data attribute in JavaScript is the name of the same HTML attribute but in camelCase and with no dashes, dots, etc.

function getComboA(selectObject) {
  const button = document.querySelector('button.js-addcart-detail');
  button.dataset.sellyProduct = selectObject.value;
  console.log(button);
}
<select class="js-select2" name="time" id="comboA" onchange="getComboA(this)">
  <option value="">Choose an option</option>
  <option value="3cffe13b">Size S</option>
  <option value="M">Size M</option>
  <option value="L">Size L</option>
  <option value="XL">Size XL</option>
</select>

<button class="flex-c-m stext-101 cl0 size-101 bg1 bor1 hov-btn1 p-lr-15 trans-04 js-addcart-detail">Add to cart</button>

Instead of using a onchange attribute, I'd suggest moving this to a separate file and use a listener instead. This allows you to better separate logic from presentation and you can add multiple listeners to the same element. You only have to make a small adjustement in t he code:

document.getElementById('comboA').addEventListener('change', function() {
  const button = document.querySelector('button.js-addcart-detail');
  button.dataset.sellyProduct = this.value; // `this` is the element receiving the event
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!