Javascript not working on submit

女生的网名这么多〃 提交于 2019-12-02 13:43:01

You have two problems:

First:

x == null && y == null

The values of the fields will never be null. If nothing has been input into them, then their value will be a empty string (i.e. ""). So you need to compare against that and not null.

Second:

document.forms["form"]["action"].value

You have multiple controls named action, so document.forms["form"]["action"] will be a NodeList (which is like an Array). It won't be a single element, and value will always be undefined.

There is no way to tell, from a submit event, which form control was used to activate the form.

Use an onclick handler on the input you care about instead.


<script>
    function validation(){
        var x = document.forms["form"]["fieldx"].value;
        var y = document.forms["form"]["fieldy"].value;
        if(x == "" && y == ""){
            return confirm("Fields have no input. Proceed at your own risk");
        }
    }
</script>

and

<input type="submit" name="action" value="delete" onclick="return validation();">

A more modern way to write it would be along these lines:

<form action="cgi-bin/process.cgi">
    <input type="text" name="fieldx">
    <input type="text" name="fieldy">
    <input type="submit" name="action" value="insert" />
    <input type="submit" name="action" value="delete" />
    <input type="submit" name="action" value="update" />
</form>
<script>
    document.querySelector('input[value=delete]').addEventListener('click', validate);
    function validate(event) {
        var elements = this.form.elements;
        if (elements.fieldx.value == "" && elements.fieldy.value == "") {
            if (!confirm("Fields have no input. Proceed at your own risk")) {
                event.preventDefault();
            }
        }
    }
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!