问题
I want to hide a class of a DIV when a specific OPTION Value is selected
<select id="tagtype" name="type">
<option value="type_s">Standard</option>
<option value="type_o">Overstock</option>
<option value="type_snd">Scratch & Dent</option>
<option value="type_mult">Multiples</option>
</select>
<div class="multiples>stuff here</div>
<script type="text/javascript">
$(document).ready(function() {
if ($("#tagtype option[value='type_mult']").length)
$("multiples").css('display','none');
});
</script>
回答1:
A better way to do this would probably be something like the following:
jQuery(document).ready(function() {
jQuery("#tagtype").change(function() {
if(jQuery(this).find("option:selected").val() == "type_mult") {
jQuery(".multiples").hide();
}
});
});
You're binding a handler to the onChange
event of the select box. Whenever, you select a new option in the select box, the handler is called.
In the handler, this
refers to the select box that fired the onChange
event. You look for the value of the selected option. If this value is equal to "type_mult", you hide all elements with the class multiples
.
The problem with your existing code is that it will only run once; when the page first finishes loading. You need to respond to changes in the select box, which is why you need to bind to the onChange
event. Another problem is the if
statement. Even if you used your code and in an onChange
handler, it enter the if
block every type because you are not checking to see if the option with the "type_mult" value is selected. You're simply checking to see if it exists. Since it always exists, the code inside the if
will always run. Also, when you want to use class names, you need to put a period in front of the class name. So you want to do $(.multiples)
and not just $(multiples)
(the latter will search for a tag named multiples
, which is not what you want).
回答2:
Needs a bit more info - what actually happens when you run this code?
My guess would be that the second jQuery selector is wrong:
$(".multiples").css('display','none');
来源:https://stackoverflow.com/questions/5328456/jquery-hide-div-when-option-is-selected