Home > other >  How to call a JS function when my form is submited
How to call a JS function when my form is submited

Time:07-28

I have this code to validate and submit a contact form:

                    if ( this.form_data.nombre &&
                         this.form_data.empresa &&
                         this.form_data.email &&
                         this.form_data.rubro &&
                         this.form_data.telefono &&
                         this.form_data.consulta_por &&
                         this.form_data.msg &&
                         this.form_data.rcapt_response
                        ) {
                        return true;
                    }
                }

But I need to call another function when this function is on "true". I don't know if i can write:

return true;
return function2();"

or if I need to write another function that checked:

if function() === true{
function2();
}

CodePudding user response:

function form_valid() {
  const data = this.form_data
  return (
    data.empresa &&
    data.email &&
    data.rubro &&
    data.telefono &&
    data.consulta_por &&
    data.msg &&
    data.rcapt_response
  )
}

// Return the result
return form_valid() && my_other_function()
// OR if you want to store the result in a variable instead of returning it
const result = form_valid() && my_other_function()

&& will continue execution until a falsy value is encountered, so this will return false if form_valid() returns false, or call my_other_function() if it returns true. Of course there's nothing wrong with an if-statement either, this is just one possible option.

Another option could be to chain one more && at the end of the form_valid() function, like this: return (... && data.rcapt_response && my_other_function()), but I wouldn't do that unless it's logically a part of ensuring that the form is valid.

CodePudding user response:

Put the call to the other function in the return statement.

if (...) {
    return function2();
}

CodePudding user response:

This code should function2 when function returns true.

if(function()){
  function2();
}
  • Related