繁体   English   中英

jQuery在最近的元素类上添加必需的属性

[英]Jquery adding a required attribute on nearest element class

当我的无线电字段值为NO时,我尝试将require属性添加到最接近的textarea ,我知道您可以对此进行专门定位,但是我的清单中有15个项目,并且我不想重复每个功能。

我的代码在下面,我能够获取该值,但未在任何最接近的textarea添加必填属性。

我的HTML

<tr>
    <td width="10">1</td>
    <td width="650">Does the stencil follow the standard size?</td>
    <td width="10"><label><input type="radio" name="q1" value="YES" required></label></td>
    <td width="10"><label><input type="radio" name="q1" value="NO" class="noq"></label></td>
    <td width="10"><label><input type="radio" name="q1" value="N/A"></label></td>
    <td><textarea rows='1' class='autoExpand' name="remarks_q1"></textarea></td>
</tr>

我的jQuery

$('.noq').on('click', function(e) {
    if(e.currentTarget.value == 'NO'){
        $(this).parent().closest('.autoExpand').prop('required',true);
    }else{
        $(this).parent().closest('.autoExpand').prop('required',false);
    }

    console.log(e.currentTarget.value);
});

我的控制台日志给出了正确的值,我也尝试了prop但是没有运气,任何建议都很棒! 提前致谢!

JQuery最接近的方法会搜索DOM树,因此您不能在此处使用它来查找文本区域。

尝试以下类似的方法,它将在DOM树中向上搜索以找到最接近的tr,然后在DOM树中向下搜索以找到您的文本区域。

$(this).closest('tr').find('.autoExpand').prop('required',true);

我添加了required类以了解更改,还为单选按钮添加了.noq类,因为该类丢失了。 并删除了else条件,因为可以避免。 而不是使用parent() ,您应该使用closes()获得最接近的tr

 $('.noq').on('click', function(e) { $(this).closest('tr').find('.autoExpand').prop('required', false).removeClass('required'); if (e.currentTarget.value == 'NO') { $(this).closest('tr').find('.autoExpand').prop('required', true).addClass('required'); } }); 
 .required { border: 1px solid #d00; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tbody> <tr> <td width="10">1</td> <td width="650">Does the stencil follow the standard size?</td> <td width="10"><label><input type="radio" name="q1" value="YES" class="noq" required></label></td> <td width="10"><label><input type="radio" name="q1" value="NO" class="noq"></label></td> <td width="10"><label><input type="radio" name="q1" class="noq" value="N/A"></label></td> <td><textarea rows='1' class='autoExpand' name="remarks_q1"></textarea></td> </tr> </tbody> </table> 

暂无
暂无

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

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