I got following problem and dont know how to solve it. :(
I want to disable / gray out options in relation to a color-selection. Every option has a unique value.
For example:
Is it possible with something like "if" or an array function?!?! Is there a code snipped on fiddle?
Thanks for any help and sorry for my non-existing JS knowledge!
<form id="test" name="test" method="post" action="">
<label for="test"></label>
<select name="color" id="color">
<option value="1">---Select color---</option>
<option value="2">T-Shirt - green</option>
<option value="3">T-Shirt - blue</option>
<option value="4">T-Shirt - yellow</option>
</select>
<br />
<select name="size" id="size">
<option value="5">---Select size---</option>
<option value="6">XS</option>
<option value="7">S</option>
<option value="8">M</option>
<option value="9">L</option>
<option value="10">XL</option>
</select>
</form>
var sizes_avail = {
'2': ['6'],
'3': ['7', '8'],
'4': ['9', '10']
};
$("#color").change(function() {
var color = $(this).val();
if (sizes_avail.hasOwnKey(color)) {
$("#size option").attr("disabled", true);
$.each(sizes_avail[color], function(i, size) {
$("#size option["+size+"]").attr("disabled", false);
}
} else {
$("#size option").attr("disabled", false);
}
}
This is pretty simple to do with the .onChange
function in jQuery along with a switch.
Assuming you can set up an object which captures the valid colours and sizes then you can iterate all the <option>
elements setting the disabled property based on whether the option's value is in the set of allowed sizes.
var availableSizesForColors = {
'2': ['6'],
'3': ['7', '8'],
'4': ['9', '10']
};
// bind the function to the JavaScript 'change' event
$('#color').change(function() {
// look up the available colours in the object above for the given value of the shirt colour drop down
var availableSizes = availableSizesForColors[this.options[this.selectedIndex].value];
// set disabled = true or false if the size option is or is not in the availableSizes array
$('#size option').prop('disabled', function () { return $.inArray(this.value, availableSizes) == -1 });
});
Note: You might wann to use a different "array contains" method if you care about the performance of the jQuert $.inArray
function - see How do I check if an array includes an object in JavaScript?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.