0

I have a survey that on button submit the first thing it runs in my js is validation if required fields are entered. Basically:

if (x == null) {
    alert("You forgot to enter a required field!.");
    return false;
};

Is there any way from preventing the page from refreshing/resetting what has previously been filled out if they forgot one required field?

This survey stores to local storage if that matters or can be used to help here.

Jonathan Naguin
  • 14,526
  • 6
  • 46
  • 75
user1
  • 347
  • 2
  • 12
  • 22

3 Answers3

1

You could use Jquerys .submit function (if using Jquery):

$('#formID').submit(function(){
    if (x == null) {
        alert("You forgot to enter a required field!.");
        return false;
    }
});
AfromanJ
  • 3,922
  • 3
  • 17
  • 33
0

Check these answer first:

if you're not interested in using a framework like jQuery this is how it could be done:

<form name="form" onsubmit="return validate()">

function validate() {
    var input_value = document.forms["form"][" .. input name .. "].value;
    if( input_value == '' ) return false;
}

If you have multiple inputs, I would suggest looping through them with a foreach loop.

With jQuery it would be something like:

$( '#formID' ).on( 'submit', function() {
    event.preventDefault();
    // check input value
    if( valid input ) $( this ).submit();
});

Interesting read: return false vs preventDefault

Community
  • 1
  • 1
Phil
  • 10,948
  • 17
  • 69
  • 101
0

Handle on submit event during form submission and return false in handler method.

code2use
  • 56
  • 3