Jump to content

Recommended Posts

I have found a lot of so-called form disable scripts which remove the functionality of the submit button, but this does not stop a user from submitting it by pressing enter.

 

Is there a way to remove the submit function of a form instead?

Well, there is nothing that will prevent it 100% since users may have JavaScript disabled. So, you'd better have some logic server-side as well.

 

Anyway, all you need to do is have a global variable to track whether the form should be submittable or not. Then add an onsubmit() trigger to the form to call a function. That function will return true/false based upon the global variable. You can get more create and also disable the submit button or show other messages to the user.

 

<html>
<head>
<script type="text/javascript">

var allowSubmit = true;

function changeSubmit(allowState)
{
    //UNCOMMENT NEXT LINE TO ALSO DISABLE SUBMIT BUTTON
    //COMMENTED OUT FOR DISPLAY PURPOSES
//  document.getElementById('submit').disabled = !allowState;
    allowSubmit = allowState;
}

function checkFormSubmitState()
{

    //ONLY THE RETURN LINE IS REQUIRED
    //THIS LINE ADDED FOR DISPLAY PURPOSES
    alert((allowSubmit)?'Form will now be submitted\nReturn true':'Submit not allowed\nReturn false')

    return allowSubmit;
}

</script>
</head>

<body>

<form onsubmit="return checkFormSubmitState();" id="test">
Field 1:<input type="text" name="field1" /><br />
Field 2:<input type="text" name="field2" /><br />
<button type="submit" id="submit">Submit Form</button>
</form>
<br /><br />

<button type="submit" onclick="changeSubmit(true);">Allow Submit</button>
<button type="submit" onclick="changeSubmit(false);">Disable Submit</button>

</body>
</html>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.