0

I am trying to prevent a submit event on a page using this code so that if I will press enter it will click the validate element.

$(document).ready(function(){
$("form").submit(function(event){
 event.preventDefault();
 document.getElementById("validate").click();//alert("Something") works fine here
 });
});

But,when I pressed enter keeping the focus on any text field it submits the form with the action assigned to the form.It is not preventing the Submit event as expected in google chrome 47. If I will place any alert rather than document.getElementById("validate").click(); then it works fine. Here is the html code for that page

<td align="center" width="100%">
<input type="button" value=" Next " id="validate" tabindex="4">
<a id="Proceed" href="#" onclick="mojarra.jsfcljs(document.getElementById('form'),{'Form:Proceed':'Form:Proceed'},'');return false"></a>
<input id="replan" type="submit" name="replan" value="Replan" tabindex="4">
</td>

So, Can anyone please explain why this is not working in newer version of chrome?(It is working fine in chrome 39)

Note: The event to id validate is assigned using addEventListener().

Swagatika
  • 23
  • 5

1 Answers1

0

I took a slightly different in similar cases, I catch the keydown on the textbox and do the preventDefault to keep the form from being submitted.

$(document).ready(function(){
    $("input[type='text']").keydown(function(evtObj){
         var code = (e.keyCode ? e.keyCode : e.which);
         if (code==13) {
            e.preventDefault();
        }
    });
});

See this discussion on key trapping jQuery - keydown / keypress /keyup ENTERKEY detection?

Community
  • 1
  • 1
Bindrid
  • 3,655
  • 2
  • 17
  • 18
  • if it is because of `keydown` event then why it is working if I replace that line with any other codes i.e `alert()`. It is not submitting form even though I pressed `Enter` – Swagatika Dec 13 '15 at 19:00
  • I guess I am still a little confused by what you are trying to accomplish. Are you just trying to validate before submit? If so, in your function, do validating. If valid return true. If not valid, do e.preventDefault and return false. – Bindrid Dec 13 '15 at 20:23