问题
I'm trying to do two things:
Show a hidden field if an option is selected, and hide that field if not (I have this part working - although if I use a variable it doesn't work)
If the option is selected, add a required attribute to the field that was displayed. When another option is selected, remove the required attribute.
Here's a fiddle link:
http://jsfiddle.net/tucsonlabs/QCY2Q/
回答1:
if ($("#aCard").filter(":selected"))
this will always pass through because jQuery always return an object and anything non zero or not null or undefined passes through if
block.
Use this if ($("#aCard").filter(":selected").length > 0)
, you can even use variable to show the required element in your fiddle take a look.
http://jsfiddle.net/QCY2Q/1/
来源:https://stackoverflow.com/questions/9284580/toggle-required-attribute-of-a-hidden-field-when-an-option-is-selected-with