简体   繁体   English

当使用jQuery选择选项时,切换(隐藏字段的)“必需”属性

[英]toggle “required” attribute (of a hidden field) when an option is selected with jQuery

I'm trying to do two things: 我正在尝试做两件事:

  1. 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) 如果选择了一个选项,则显示一个隐藏的字段,否则,则隐藏该字段(我有这部分在工作-尽管如果我使用变量则行不通)

  2. 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/ http://jsfiddle.net/tucsonlabs/QCY2Q/

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. if ($("#aCard").filter(":selected"))将始终通过,因为jQuery始终返回对象,并且非零,非null或未定义的任何内容都将通过if块传递。

Use this if ($("#aCard").filter(":selected").length > 0) , you can even use variable to show the required element in your fiddle take a look. if ($("#aCard").filter(":selected").length > 0)使用此if ($("#aCard").filter(":selected").length > 0) ,则甚至可以使用变量来显示小提琴中所需的元素。

http://jsfiddle.net/QCY2Q/1/ http://jsfiddle.net/QCY2Q/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM