根据属性更改选择选项

时间:2016-06-10 13:47:19

标签: javascript jquery html

我正在尝试更改SELECT D.*, P.Param FROM Dataset D INNER JOIN DatasetParam P ON D.ID = P.DatasetID 上的select option,但我不想使用click。如果我给我的按钮option value,我的代码就有效,但我想要的是选择带有value='3'的按钮,在我的情况下是data-price="0"。{/ p>

JS:

value='3'

Html:

jQuery(document).ready(function () {
    jQuery('#sample-addtocart-button').click(function(){
        jQuery('.product-custom-option').val(jQuery(this).attr('value'));
    });
});

任何帮助将不胜感激

3 个答案:

答案 0 :(得分:4)

您可以使用attribute equals selector获取该选项,然后使用 prop() 方法设置selected属性,从而选择该选项。

jQuery(document).ready(function() {
  jQuery('#sample-addtocart-button').click(function() {
    jQuery('.product-custom-option option[data-price="' + jQuery(this).attr('value') + '"]').prop('selected', true);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button value="0" id="sample-addtocart-button" type="button">Free</button>

<select class="product-custom-option">
  <option value="">-- Please Select --</option>
  <option data-price="10" value="1">£10.00</option>
  <option data-price="20" value="2">£20.00</option>
  <option data-price="0" value="3">FREE</option>
</select>

答案 1 :(得分:1)

您可以按属性选择元素,然后在元素上设置selected属性。

jQuery(document).ready(function () {
    jQuery('#sample-addtocart-button').click(function(){
        jQuery('.product-custom-option [data-price=' + this.value + ']').prop("selected", true);
    });
});

这将选择data-price属性等于this.value的值的元素,.product-custom-optionselected的后代,并将其true属性设置为{{1 }}

没有jQuery,它可能看起来像这样:

document.addEventListener("DOMContentLoaded", function () {
  document.querySelector('#sample-addtocart-button').addEventListener("click", function(){
    document.querySelector('.product-custom-option [data-price=' + this.value + ']').selected = true;
  });
});

少数帮助方法总是有助于详细说明:

function listen(el, typ, fn, cap) {
  el && el.addEventListener(typ, fn, cap)
}
function query(el, sel) {
  if (typeof el === "string") {
    sel = el;
    el = document;
  }
  return el.querySelector(sel)
}

listen(document, "DOMContentLoaded", function () {
  listen(query('#sample-addtocart-button'), "click", function(){
    query('.product-custom-option [data-price=' + this.value + ']').selected = true;
  });
});

答案 2 :(得分:0)

试试这个:

jQuery('#sample-addtocart-button').click(function(){
        var val= jQuery(this).attr('value');
        jQuery('.product-custom-option option[data-price='+val+']').prop('selected', true); // it will find the select option with certain data-price and make it selected
});
相关问题