[英]Validate select Input fields based on what is selected in option menu
好的,所以我有一個需要驗證的表格/表單,請確保提交時沒有空白的輸入字段。 要注意的是,我只需要根據表頂部的選定選項對某些字段進行驗證。
需要: Op1->名稱,城市,州,電話,郵政編碼。
需要: Op2->名稱,城市,州,電話,郵政編碼,ssn。
需要: Op3->名稱,城市,州,電話,郵政編碼,ssn。
需要: Op4->名稱,城市,州,電話,郵政編碼,DOB等。
我想知道我是要以正確的方式進行操作,還是有更好的方法來進行此操作。
旁注:選項值是從后端動態創建的,我無法將任何ID /值添加到選項標簽中。
<div class="container">
<form action="">
<table id="mytable1">
<tr>
<td>
<select>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
<option>Option 4</option>
</select>
</td>
</tr>
<tr>
<td>
<label for="">Name</label>
<input type="text" class="name">
</td>
</tr>
<tr>
<td>
<label for="">City</label>
<input type="text" class="city">
</td>
</tr>
<tr>
<td>
<label for="">Phone</label>
<input type="text" class="phone">
</td>
</tr>
<tr>
<td>
<label for="">State</label>
<input type="text" class="state">
</td>
</tr>
<tr>
<td>
<label for="">zip</label>
<input type="text" class="pos">
</td>
</tr>
<tr>
<td>
<label for="">SSN:</label>
<input type="text" class="add1">
</td>
</tr>
<tr>
<td>
<label for="">DOB:</label>
<input type="text" class="add1">
</td>
</tr>
<tr>
<td>
<label for="">other:</label>
<input type="text" class="add1">
</td>
</tr>
</table>
</form>
<button onclick="">Submit</button>
<p>Values: </p>
</div>
和加入的JavaScript
$(document).ready(function () {
$('select').on('change', function () {
$( "p" ).append($( "input" ).map(function() {
return $( this ).val();
}).get().join( ", " ) );
$('table').append($('input').map(function () {
console.log($(this).val());
}).get().join(', '));
let selValue = $('select option:selected').text();
if(selValue == 'Option 1'){
//check if required fields are blank, if so throw error
console.log('value 1 is selected');
}else if(selValue == 'Option 2'){
//check if required fields are blank, if so throw error
console.log('value 2 is selected');
} else if(selValue == 'Option 3'){
//check if required fields are blank, if so throw error
console.log('value 3 is selected');
}else if(selValue == 'Option 4'){
//check if required fields are blank, if so throw error
console.log('value 4 is selected');
}else {
//submit form.
//$("form").submit();
}
});
如果還有其他需要的信息,請告訴我,我會盡快發布。
您需要解決的問題很少-
1)表單標簽關閉時還應包括“提交”按鈕。
2)如果您使用該按鈕提交表單,則將type="submit"
作為屬性添加到表單。
檢查此小提琴以進行驗證-https: //jsfiddle.net/8o0smzth/3/
我已經注釋掉了部分代碼。 請隨時詢問您是否還有其他問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.