如何将类添加到相邻元素的input元素?

时间:2022-10-31 22:23:58
($(this).addClass("error")

adds the class error to select upon validation. But along with it i also want to add this class to the input field inside next <span>. This is am doing to solve my problem stated here. I think it can be done like this.

添加类错误以在验证时选择。但与此同时,我还想将此类添加到下一个中的输入字段。这是为了解决我在这里陈述的问题。我认为可以这样做。

Following is the html where i want to add the class="error"

以下是我要添加class =“error”的html

<select data-placeholder="Pick the ones that apply to you" multiple="" class="js-selection select2-hidden-accessible error" name="option" data-placement="left" data-toggle="tooltip" data-required="true" tabindex="-1" aria-hidden="true" placeholder="Please fill out this field">
                        <option selected="" value=""></option>
                        <option value="1">Shipping / post</option>
                        <option value="2">Customers can collect</option>
                        <option value="3">Other</option>
</select>

<span class="select2 select2-container select2-container--default" dir="ltr" style="width: auto;">
 <span class="selection">
   <span aria-expanded="false" aria-haspopup="true" aria-autocomplete="list" role="combobox" class="select2-selection select2-selection--multiple" tabindex="0">
     <ul class="select2-selection__rendered">
       <li class="select2-search select2-search--inline">
          <input type="search" role="textbox" spellcheck="false" autocapitalize="off" autocorrect="off" autocomplete="off" tabindex="-1" class="select2-search__field" placeholder="Pick the ones that apply to you" style="width: 0px;">
       </li>
     </ul>
    </span>
 </span>
<span aria-hidden="true" class="dropdown-wrapper"></span></span>

1 个解决方案

#1


Based on your explanation this is the select, so you can do it this way:

根据你的解释,这是选择,所以你可以这样做:

$(this).addClass('error');
$(this).next().find('input').addClass('error');

You can combine them too into one operation using add():

您可以使用add()将它们组合到一个操作中:

$(this).add($(this).next().find('input')).addClass('error');

#1


Based on your explanation this is the select, so you can do it this way:

根据你的解释,这是选择,所以你可以这样做:

$(this).addClass('error');
$(this).next().find('input').addClass('error');

You can combine them too into one operation using add():

您可以使用add()将它们组合到一个操作中:

$(this).add($(this).next().find('input')).addClass('error');