我希望在产品X选择optgroup
时隐藏其他display: none
(main1
) - main2仅显示产品X数量并隐藏其他Y和Z.
<select id="MAIN1" name="MAIN1" onchange="calculate()">
<option selected>SELECT PRODUCT TYPE</option>
<option id="1" >PRODUCT X</option>
<option id="2" >PRODUCT Y</option>
<option id="3" >PRODUCT Z</option>
</select>
<select id="MAIN2" name="MAIN2" onchange="calculate()">
<option selected>SELECT WEIGHT & QUANTITY</option>
<optgroup id="11" label="PRODUCT X">
<optgroup id="111" label="1KG">
<option value="50">1 POUCH</option>
<option value="100">2 POUCH</option>
<option value="150">3 POUCH</option>
<option value="200">4 POUCH</option>
</optgroup>
</optgroup>
<optgroup id="22" label="PRODUCT Y">
<optgroup id="222" label="1KG">
<option value="150">1 POUCH</option>
<option value="300">2 POUCH</option>
<option value="450">3 POUCH</option>
<option value="600">4 POUCH</option>
</optgroup>
</optgroup>
<optgroup id="33" label="PRODUCT Z">
<optgroup id="333" label="1KG">
<option value="300">1 POUCH</option>
<option value="600">2 POUCH</option>
<option value="950">3 POUCH</option>
<option value="1000">4 POUCH</option>
</optgroup>
</optgroup></optgroup>
</select>
答案 0 :(得分:2)
jQuery和Pure JS版本:
很抱歉,您无法将optgroup标记放入其他optgroup标记中。
// Pure JS version
window.onload = function(){
var main1 = document.querySelector('#MAIN1');
var onchanged = function(){
var this_ = this;
var value = this_.value;
var main2 = document.querySelector("#MAIN2");
var alloption = main2.querySelectorAll('optgroup[label*="PRODUCT"]')
var getByLabel = main2.querySelector('[label="'+value+'"]');
alloption.forEach(function(element){
element.style.display = "none";
});
getByLabel.style.display = "block";
};
main1.onchange = onchanged;
};
// Jquery Version.
/*
$(document).ready(function(){
$('#MAIN1').on('change',function(){
var this_ = $(this);
var value = this_.val();
var main2 = $("#MAIN2");
var alloption = main2.find('optgroup[label*="PRODUCT"]')
var getByLabel = main2.find('[label="'+value+'"]');
alloption.hide()
getByLabel.show()
});
});
*/
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="MAIN1" name="MAIN1" >
<option selected>SELECT PRODUCT TYPE</option>
<option id="1" >PRODUCT X</option>
<option id="2" >PRODUCT Y</option>
<option id="3" >PRODUCT Z</option>
</select>
<select id="MAIN2" name="MAIN2" >
<option selected>SELECT WEIGHT & QUANTITY</option>
<optgroup id="11" label="PRODUCT X">
<option value="50">1 POUCH</option>
<option value="100">2 POUCH</option>
<option value="150">3 POUCH</option>
<option value="200">4 POUCH</option>
</optgroup>
<optgroup id="22" label="PRODUCT Y">
<option value="150">1 POUCH</option>
<option value="300">2 POUCH</option>
<option value="450">3 POUCH</option>
<option value="600">4 POUCH</option>
</optgroup>
<optgroup id="33" label="PRODUCT Z">
<option value="300">1 POUCH</option>
<option value="600">2 POUCH</option>
<option value="950">3 POUCH</option>
<option value="1000">4 POUCH</option>
</optgroup>
</select>
&#13;