javascript - 向表单添加第二个提交按钮会使脚本无法在同一表单中找到元素
问题描述
我有一个带有两个按钮的表单。为了能够更好地排列按钮,我将它们放在了一个 div 中。
通过在同一表单上添加第二个按钮,其中一个脚本返回:Uncaught TypeError: Cannot read properties of null (reading 'includes')
.
<form class="tab-pane active" id="input" name="input">
<!-- Input row -->
<span>Input 1 Address:</span>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="IP-Address"
aria-label="Input 1 IP Address" name="ip_1" id="ip_1"
onchange="ValidateIPaddressOnChange(this)">
<span class="input-group-text">:</span>
<input type="text" class="form-control" placeholder="Port"
aria-label="Input 1 Port" name="port_1" id="port_1" pattern="\d*"
maxlength="5">
</div>
<!-- Submit Buttons -->
<div class="buttons d-flex justify-content-between">
<button class="btn btn-success" type="submit" name="save_io">Save</button>
<button class="btn btn-danger" type="submit" name="reset_io">Reset</button>
</div>
</form>
脚本:
function ValidateIPaddress(form) {
console.log(form.elements[0].ariaLabel);
for (let i = 0; i < form.elements.length - 1; i++) {
// Select only the ip Address inputs
if (form.elements[i].ariaLabel.includes("Address")) {
if (form.elements[i].ariaLabel.includes("Network") && form.elements[i].placeholder != 'DHCP IP' &&
!form.elements[i].value.match(ipformat)) {
alert(`You have entered an invalid ${form.elements[i].ariaLabel}!`);
form.elements[i].focus();
return false;
} else if (form.elements[i].value.length > 0 && !form.elements[i].value.match(ipformat)) {
alert(`You have entered an invalid ${form.elements[i].ariaLabel}!`);
form.elements[i].focus();
return false;
}
}
}
return true;
}
let input_form = document.getElementById("input");
input_form.addEventListener("submit", function (e) {
e.preventDefault();
if (ValidateIPaddress(input_form)) {
saveSettings(input_form, "input/post");
input_form.reset();
}
});
奇怪的是console.log(form.elements[0].ariaLabel);
返回Input 1 IP Address
,这是正确的,那么为什么:
if (form.elements[i].ariaLabel.includes("Address"))
返回
Uncaught TypeError: Cannot read properties of null (reading 'includes')
?
解决方案
推荐阅读
- r - 基于单词列表的分类 R
- arrays - 如何在 TypeScript 中定义具有不同类型项目和特定顺序的数组类型?
- java - PMD CallSuperInConstructor 的原因是什么?
- javascript - 循环遍历层次结构树并从中创建一个 REACT UI
- ios - 弹出日期选择器以设置日期
- aws-lambda - 使用 jenkins 和 aws cli 发布 aws lambda 版本
- c# - 在二维数组中分配值不起作用 - 交换索引
- javascript - 未处理的“错误”事件。(TypeError:无法读取 null 的属性“标题”)
- javascript - 这个 RGB 到 HSV 颜色转换方程我做错了什么?
- r - 两列合并为一但合并再次创建两列