将复选框与输入字段相关联,并且仅当输入值存在时才将其设为必选

时间:2019-01-10 10:23:38

标签: javascript html

我正在尝试建立一个手动验证系统,希望用户在提交之前检查与各个输入相关联的每个checkbox是否存在值,否则表单将引发错误。

我已经实现了它,但是它似乎没有用。另外,我想知道是否有更好的方法可以避免将参数传递给函数。

类似于我们如何通过提供form来使用id将表单的提交按钮关联起来。

<form>

    <input type="text" name="inputFieldOne">
    <input type="checkbox" onblur="makeSureItIsSelected('inputFieldOne', 'inputCheckboxOne')" name="inputCheckboxOne">

    <input type="text" name="inputFieldTwo">
    <input type="checkbox" onblur="makeSureItIsSelected('inputFieldTwo', 'inputCheckboxTwo')" name="inputCheckboxTwo">

    <input type="submit" value="Submit">

</form>

<script>

    function makeSureItIsSelected(field, checkbox){
        let fieldBox = document.getElementsByName(field)[0];
        if(fieldBox.value != ''){
            checkBox = document.getElementsByName(checkbox)[0];
            checkBox.required = true;
        }
    }

</script>

1 个答案:

答案 0 :(得分:2)

如果要设置该字段具有值时必需的复选框,则应在 field 而不是复选框上挂一个事件。 input为此将是一件好事:

function makeSureItIsSelected(field, checkbox){
    let fieldBox = document.getElementsByName(field)[0];
    let checkBox = document.getElementsByName(checkbox)[0];
    // Require the checkbox when the field has a value
    checkBox.required = fieldBox.value != '';
}
<form>

    <input type="text" name="inputFieldOne" oninput="makeSureItIsSelected('inputFieldOne', 'inputCheckboxOne')">
    <input type="checkbox" name="inputCheckboxOne">

    <input type="text" name="inputFieldTwo" oninput="makeSureItIsSelected('inputFieldTwo', 'inputCheckboxTwo')">
    <input type="checkbox" name="inputCheckboxTwo">

    <input type="submit" value="Submit">

</form>

请注意,无需对getElementsByName进行这些调用:只需将this传递到函数中,然后使用nextElementSibling来访问复选框:

function makeSureItIsSelected(field){
    // Require the checkbox when the field has a value
    field.nextElementSibling.required = field.value != '';
}
<form>

    <input type="text" name="inputFieldOne" oninput="makeSureItIsSelected(this)">
    <input type="checkbox" name="inputCheckboxOne">

    <input type="text" name="inputFieldTwo" oninput="makeSureItIsSelected(this)">
    <input type="checkbox" name="inputCheckboxTwo">

    <input type="submit" value="Submit">

</form>


也就是说,根本没有复选框。表单数据中字段的存在应足够。但是,如果该复选框的值必须包含在表单数据中,则只需在提交时将其添加而无需任何复选框。

相关问题