简体   繁体   English

为孩子元素添加类取决于jQuery的输入值

[英]Add class for children element depend on input value with jQuery

I have two fieldsets : 我有两个fieldsets

<fieldset class="checkable">
   <span class="as_cp_checkbox"></span>
   <input type="hidden" name="register_condition_01" id="register_condition_01" value="no">
   <label for="register_condition_01">data</label>
</fieldset>
<fieldset class="checkable">
   <span class="as_cp_checkbox"></span>
   <input type="hidden" name="register_condition_02" id="register_condition_02" value="yes">
   <label for="register_condition_02">data</label>
</fieldset>

Now: i need to add checked class to span.as_cp_checkbox if in my input value is yes. 现在:如果我的输入值为yes,则需要将checked类添加到span.as_cp_checkbox I try with that but every time this class is appending for first fieldset . 我尝试过,但是每次此类添加到第一个fieldset

var checkable_fieldset = $('fieldset.checkable'),
    checkable_fieldset_input = checkable_fieldset.find('input');
if (checkable_fieldset_input.val('yes')){
    checkable_fieldset_input.parent(checkable_fieldset).prev().children('span').addClass('checked');
}

How can i add class for this prev span which input have yes value? 如何为该上一个span添加类,这些input具有yes值?

You can do this to add the class checked to all 'span.as_cp_checkbox' preceding an input whose value is "yes" : 您可以这样做,将checked的类添加到所有值为"yes"的输入之前的所有'span.as_cp_checkbox' "yes"

$('input').filter(function(){return $(this).val()=="yes";})
 .prev('span.as_cp_checkbox')
 .addClass('checked');

Demonstration 示范

checkable_fieldset_input.val('yes') sets the value to yes. checkable_fieldset_input.val('yes')将该值设置为yes。 you need to do checkable_fieldset_input.val() == 'yes' 您需要执行checkable_fieldset_input.val() == 'yes'

Your condition in the if statement should read if语句中的条件应为

checkable_fieldset_input.val() == 'yes'

Right now you are assigning the value yes. 现在,您正在分配值yes。

$('fieldset.checkable input').each(function(_, input){
    if($(input).val() == 'yes')
    {
        $(input).siblings('span.as_cp_checkbox').addClass('checked');
    }
});

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

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