首页 > 解决方案 > 向表单添加第二个提交按钮会使脚本无法在同一表单中找到元素

问题描述

我有一个带有两个按钮的表单。为了能够更好地排列按钮,我将它们放在了一个 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')

标签: javascripthtml

解决方案


推荐阅读