Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Form That Doesn't Actually Submit Anything To The Server (Client-Side Processing in JavaScript)

I have an HTML form with inputs that will only do client-side processing in JavaScript and jQuery, but won't actually submit anything to the server. What is the proper way of laying out out such a form in HTML and writing JavaScript that will process a form when the form's inputs change (both on an explicit submit event (i.e. clicking 'Submit' or Enter), or on an implicit change event (un-focusing from an input, or even on every keystroke/click of an input's text))?

like image 287
Paul Rudd Avatar asked Aug 27 '26 11:08

Paul Rudd


2 Answers

Firstly prevent the default form action by returning false in the onsubmit or by using event.preventDefault() in the event handler.

Inline:

<form id="myform" onsubmit="return false" action="pleaseturnonjavascript.html">

better:

window.onload=function() {
  document.getElementById("myform").onsubmit=function() {
    // do something with the form field
    return false; // old way
  }
}

using preventDefault:

window.onload=function() {
  document.getElementById("myform").onsubmit=function(e) {
    e.preventDefault(); // first statement
    // do something with the form field
  }
}

or jQuery:

$(function() {
  $("#myform").on("submit",function(e) {
    e.preventDefault(); // first statement
    // do something with the form field
  });
});

then decide if you want to use onkeyup (I use that in number fields) or onblur (used when the complete value is important)

This can be done using plain old JavaScript or jQuery, but we need more information to help you further

I prefer using the form tag and pass the form object instead of just have input fields that have to be accessed per field instead of using the form elements array - I feel unhappy not wrapping inputs in a form tag. It might not even validate and the added benefit is that enter will trigger the submit event without other measures.

like image 80
mplungjan Avatar answered Aug 29 '26 02:08

mplungjan


If you really never submit the form to somewhere, you can avoiding use a form tag at all. And just use input boxes and buttons. Then if the user clicks the button, either your click handler runs, or nothing happens at all.

As for catching the explicit events, button click, unfocus (blur) I would suggest jQuery as it makes it really easy to attach handlers to those events in a cross-browser way.

  • http://api.jquery.com/click/
  • http://api.jquery.com/blur/
  • http://api.jquery.com/keyup/
like image 25
ctcherry Avatar answered Aug 29 '26 00:08

ctcherry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!