• Want to receive the latest contracting news and advice straight to your inbox? Sign up to the ContractorUK newsletter here. Every sign up will also be entered into a draw to WIN £100 Amazon vouchers!

Jscript to stop enter submitting form

xoggoth

More fingers than teeth
Joined
Jul 8, 2005
Messages
17,131
Likes received
4,950
Thanks received
1,184
Location
xoggoth towers
Trying to write some online invoicing software and want to prevent submitting partially filled form with enter. Used the solutions on the net, ie
stuck onkeydown='noenter();' on inputs and added some jscript:

function noenter()
{
var x = event.which || event.keyCode;
if (x == 13) return false;
}

Put same event code in the jscript on submit form validation and eventually got it to almost work by sticking onkeydown on ALL controls, even disabled ones, but if a control has been selected (even a disabled one!) and then enter is pressed it submits.

Sounds trivial I know, but this is for a severely untechy person and it needs to be foolproof as possible. Any ideas why having a selected control causes the jscript to be ignored? Cheers.
 
Last edited: 15:23
Try something like:

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


function disableEnter(e) {
  if(e.which==13 || e.keyCode==13) 
  {
    e.preventDefault();
  } 
}

</script>
</head>
<body>
<form method="post" onkeypress="disableEnter(window.event)">
<input type=text/>
<input type="submit"/>
</form>
</body>
</html>
 
Ignore the above - doesn't work in IE10
 
Code:
function checkIfTheFormIsReadyToBeSubmittedYetOrIfTheyMissedABit() {
    // check stuff here...
    if (everythingIsOk) {
        return true;
    }
    return false;
}

document.getElementById("theForm").onsubmit = checkIfTheFormIsReadyToBeSubmittedYetOrIfTheyMissedABit;
// N.B. No brackets at the end of the line above is intentional - we want to assign the function, not the result of calling it :-)

should do it - also stops them submitting it via the submit button, which you presumably also don't want if the form isn't complete :)
 

Advertisers

Back
Top