Reputation: 13
Scenario: I am selling a T-shirt in pink, navy, black and size small, medium and large. I've got two selection boxes, one for color and the other for size. I'm sold out of medium pink T-shirts, so need to disable this option. How can I disable the 'Medium' option when 'Pink' is selected, but ensure that it's active for the other color options?
<select name="product[]" id="color">
<option value="Pink">Pink</option>
<option value="Navy">Navy</option>
<option value="Black">Black</option>
</select>
<select name="product[]" id="size">
<option value="Small">Small</option>
<option value="Medium">Medium</option>
<option value="Large">Large</option>
</select>
I've had a punch at solving this issue myself but can't seem to get it to work. I need a solution which works with option values with letters and spaces i.e. 'Dark Pink' or 'Extra Large', as the option values are passed forward to the checkout. This is the closest I've gotten to a solution:
function enableElements()
{
if($('#color').val() == "pink"){
$("#size option[value='medium']").attr('disabled',true);
}
else $("#size option[value='medium']").attr('disabled',false);
}
^ This is based upon the article found here: http://www.codeoncall.com/disable-drop-down-list-items-based-on-another-drop-down-selection/.
Upvotes: 0
Views: 9444
Reputation: 1392
a better , or i can say a faster approach would be as following snippet.
$("#size").find("option[value='Medium']").prop('disabled',true)
Upvotes: 0
Reputation: 430
Here is an alternative method:
function enableElements() {
if ($('#color').val() == "pink") {
$("#size").children().each(function() {
if ($(this).val() == 'medium') {
$(this).prop('disabled',true);
}
});
} else {
$("#size").children().each(function() {
if ($(this).val() == 'medium') {
$(this).prop('disabled',false);
}
});
}
}
Upvotes: 0
Reputation: 5211
Try this:
$('#color').change(function(e){
if($(this).val() == "Pink"){
$("#size option[value='Medium']").prop('disabled',true);
}
else {
$("#size option[value='Medium']").prop('disabled',false);
}
});
Use 'prop' instead of 'attr'.
Demo:
Upvotes: 3