Jump to content

Disable a form by removing the submit function


gerkintrigg

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>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.