HTML form action and onsubmit issues

2019-01-04 11:33发布

I am wanting to run javascript user validation on some textbox entries.

The problem I'm having is that my form has the action of going to a new page within our site, and the onsubmit attribute never runs the javascript function.

Is there a better solution, or one that works with the following code: NOTE: the javascript file is written correctly and works if you switch the action to checkRegistration().

It is merely an issue with running both action and javascript.

<form name="registerForm" action="validate.html" onsubmit="checkRegistration()" method="post">
    <!-- textboxes here -->
    <!-- and submit button -->
</form>

2条回答
Animai°情兽
2楼-- · 2019-01-04 11:53

Try

onsubmit="return checkRegistration()"
查看更多
Ridiculous、
3楼-- · 2019-01-04 11:56

You should stop submit procedure by returning false on onsubmit callback.

<script>
function checkRegistration(){
    if(!form_valid){
        alert('Given data is not correct');
        return false;
    }
    return true;
}
</script>
<form onsubmit="return checkRegistration()"...

UPDATE:

here you have fully working example, form will submit only when you write google into input, otherwise it will return error:

<script>
function checkRegistration(){
    var form_valid = (document.getElementById('some_input').value == 'google');
    if(!form_valid){
        alert('Given data is incorrect');
        return false;
    }
    return true;
}
</script>
<form onsubmit="return checkRegistration()" method="get" action="http://google.com">
    Write google to go to google..<br/>
    <input type="text" id="some_input" value=""/>
    <input type="submit" value="google it"/>
</form>
查看更多
登录 后发表回答