[英]how to add required attribute only if another input is not empty with javascript/jquery?
我在表單中有一個列表,因此在每個列表項中都有2個輸入。
我希望在提交表單時,如果我在同一列表上的2個輸入之一不為空,則應同時滿足它們(必需屬性),但是如果在其他列表項上2個輸入為空,則將其作為他們是。
這是僅一個列表項的示例:
<form class="settings-form quick-reports">
<ul class="report-list">
<li class="report-list-li">
<span class="report-num">Report 01</span>
<div class="settings-name-fields">
<label for="website-name1" class="report-name">Name</label>
<input class="website-input" type="text" id="website-name1">
</div>
<div class="settings-url-fields">
<label for="website-url1" class="report-url">URL</label>
<input class="url-input" type="url">
</div>
</li>
</ul>
</form>
想過類似的事情:
$('#submit').click(function(e){
if($(input1).val() !== ""){
$('input1').prop('required', true);
$('input2').prop('required', true);
}
});
但是我不知道如何做到這一點並使它適合我列表中的每個列表項
我的整個小提琴在這里
這應該可以滿足您的需求:
使用.each()
循環:
$('#submit').click(function(e){
// remove required property in case that some fields were modified before click
$('.report-list input').prop('required', false).each(function(){
!$(this).val() || $(this).closest('li').find('input').prop('required', true);
});
});
或.filter()
:
$('#submit').click(function(e){
$('.report-list input').prop('required', false).filter(function(){
return $(this).val();
}).closest('li').find('input').prop('required', true);
});
我建議不要使用此處required
的屬性,首先,此屬性不適用於所有瀏覽器(例如,IE只會忽略它),其次,可能是在提交時設置它為時已晚。
我會用這樣的東西:
if($(input1).val() == "" && $(input2).val()==""){
//handle case and show error message
alert("Either input one or input2 needs a value");
e.preventDefault();
return false; //make sure the form is not submitted
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.