Reputation: 1872
I am trying to auto-select an option in a drop down when a specific image is clicked, I have made a JsFiddle to show my current code, can anyone point me in the right direction?
Link: 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);
});
At the moment the console displays this:
Click is being run, search has been varred as: 01
Oh, and I found the option, value is: undefined
Cheers
Upvotes: 0
Views: 711
Reputation: 20626
Use this Demo Fiddle
$('.product-option-select').find('option:contains(' + search + ')')
find('option[text=' + search + ']')
is a wrong selector in this case. Use :contains()Full JS code- modified :
$('.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);
});
Alternative to :contains()
,
$(".product-option-select option").filter(function () {
return $.trim($(this).text()) == search;
}).attr('selected', 'selected');
Upvotes: 1