[英]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.