javascript - 根据选项菜单中选择的内容验证选择输入字段
问题描述
好的,所以我有一个需要验证的表格/表格,确保提交时没有空白输入字段。问题是我只需要根据表格顶部的选定选项验证某些字段。
需要: Op1 -> 姓名、城市、州、电话、邮编。
需要: Op2 -> 姓名、城市、州、电话、邮编、ssn。
需要: Op3 -> 姓名、城市、州、电话、邮编、ssn。
需要: Op4 -> 姓名、城市、州、电话、邮编、出生日期、其他。
我想知道我是否以正确的方式解决这个问题,或者也许有更好的方法来解决这个问题。
旁注:选项值是从后端动态创建的,我无法将任何 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/
我已经注释掉了您的部分代码。如果您有更多问题,请随时提出。
推荐阅读
- python-3.x - 如何加入标签列表而不将它们转换为字符串?
- javascript - 从 AJAX 发送文件并从 PHP 检索
- css - 悬停时放大图像并覆盖其他图像
- node.js - 用户有邀请时添加角色的问题
- vue.js - 使用 Quasar (Vue) 进行服务器端输入验证
- javascript - 在用户单击的位置向页面添加随机图像
- solr - 如何在 SolrJ 中指定默认搜索字段
- javascript - (Vue.js) 类绑定不适用于引用另一个数据属性的变体
- python - 需要代码让用户重复尝试
- android - kotlin android Realm DB 创建外键(链接对象)