jQuery Auto - 在下拉列表中选择一个选项

时间:2014-06-02 11:48:38

标签: jquery

我想在单击特定图像时自动选择下拉列表中的选项,我已经制作了一个JsFiddle来显示我当前的代码,是否有人能指出我正确的方向?

链接:http://jsfiddle.net/CWTx6/

HTML:

<img class="auto-image" data-name="01" style="cursor:pointer;" src="img/Plaque/Horses/01.png">

<select name="productOption[]" id="product-option-11" class="product-option product-option-select" data-force="0" data-title="Image">
    <option value="0" data-price="0">Please select...</option>
    <option value="11::167" data-price="0.0000" data-modify="0">01</option>
</select>

JS:

$('.auto-image').on('click', function() {
    var search = $(this).data('name');
    console.log('Click is being run, search has been varred as: ' + search);

    $('.product-option-select').find('option[text=' + search + ']').attr('selected', 'selected');

    var found = $('.product-option-select').find('option[text=' + search + ']').val();
    console.log('Oh, and I found the option, value is: ' + found);
});

控制台显示此时:

Click is being run, search has been varred as: 01
Oh, and I found the option, value is: undefined 

干杯

1 个答案:

答案 0 :(得分:1)

使用此 Demo Fiddle

$('.product-option-select').find('option:contains(' + search + ')')

    在这种情况下,
  1. find('option[text=' + search + ']')是一个错误的选择器。使用 :contains()
  2. 你没有在你的小提琴中包含对jQuery的引用。

  3. 完整的JS代码修改:

    $('.auto-image').on('click', function() {
        var search = $(this).data('name');
        console.log('Click is being run, search has been varred as: ' + search);
    
        $('.product-option-select').find('option:contains(' + search + ')').attr('selected', 'selected');
    
        var found = $('.product-option-select').find('option:contains(' + search + ')').val();
    
        console.log('Oh, and I found the option, value is: ' + found);
    });
    

    替代:contains()

    $(".product-option-select option").filter(function () {
        return $.trim($(this).text()) == search;
    }).attr('selected', 'selected');