如何添加'required'属性来输入textarea的更改? [英] How can I add the 'required' attribute to input on change of textarea?
本文介绍了如何添加'required'属性来输入textarea的更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在textarea(orderComments)中输入文本的条件下,将所需的属性添加到html选择(toDept)。以下是我的代码...我错过了什么?我需要在变化事件或其他事情上运行我的jQuery吗?
$(document).ready(function(){if($ '#textareaId')。val()!=''){$(#selectId)。attr('required',true);}}
< script src =https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery。 min.js>< / script>< textarea id =textareaId>< / textarea>< select id =selectId>< option value =>< / option> < option value =opt1> opt1< / option>< / select>
感谢您的时间!
解决方案
您需要在textarea更改时运行代码:
var textarea = $('#textareaId');
var select = $( '#selectId');
var addOrRemoveRequiredAttribute = function(){
if(textarea.val()。length){
select.attr('required',true) ;
}
else {
select.attr('required',false);
}
};
//立即运行
addOrRemoveRequiredAttribute();
//当textarea改变
时textarea.on('change',addOrRemoveRequiredAttribute);
I need to add the required attribute to an html select (toDept) under the condition that a textarea (orderComments) has text typed in it. Below is my code... What am I missing? Do I need to run my jquery on a change event or something?
$(document).ready(function() {
if ($('#textareaId').val() != '') {
$("#selectId").attr('required', true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="textareaId"></textarea>
<select id="selectId">
<option value=""></option>
<option value="opt1">opt1</option>
</select>
Thanks for your time!
解决方案
You need to run the code when the textarea changes:
var textarea = $('#textareaId');
var select = $('#selectId');
var addOrRemoveRequiredAttribute = function () {
if (textarea.val().length) {
select.attr('required', true);
}
else {
select.attr('required', false);
}
};
// Run now
addOrRemoveRequiredAttribute();
// And when textarea changes
textarea.on('change', addOrRemoveRequiredAttribute);
这篇关于如何添加'required'属性来输入textarea的更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文