简体   繁体   English

提交表单时如何调用 JS function

[英]How to call a JS function when my form is submited

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".但是当这个 function 为“真”时,我需要调用另一个 function。 I don't know if i can write:我不知道我是否可以写:

return true;
return function2();"

or if I need to write another function that checked:或者如果我需要编写另一个检查过的 function:

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

Put the call to the other function in the return statement.将调用另一个 function 放在return语句中。

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

This code should function2 when function returns true.当 function 返回 true 时,此代码应该起作用。

if(function()){
  function2();
}
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 . &&将继续执行直到遇到虚假值,因此如果form_valid()返回false ,则返回false ,如果返回true ,则调用my_other_function() Of course there's nothing wrong with an if -statement either, this is just one possible option.当然if语句也没有错,这只是一种可能的选择。

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.另一种选择可能是在form_valid() function 的末尾再链接一个&& ,如下所示: return (... && data.rcapt_response && my_other_function()) ,但我不会这样做,除非它在逻辑上是确保表格有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM