简体   繁体   中英

Save javascript generated errors

My question is if there a way to before send a form, it is possible to get in a javascript string variable the errors that can be fired while the user is working on the elements of the form.

These elements are used to make mathematics operations to add or subtract and sometimes I get an incorrect final value after this operations.

If you do not understand well my question, please tell me to try to explain better.

Regards.

If you are talking about Validation , then use the form's onsubmit method and return true/false based on your condition.

Or if it is about saving Errors : if you think, your JS code will throw an unknown error at runtime, say in function someFuntion and you want to analyse at later point.

Then cover the code block in someFunction with try-catch and in catch do Ajax to store the errors in your DB, later you can analyse it.

function someFunction() {
    ....
    try {
        ...
    } catch(e) {
        //do Ajax('formatted e');
    }
}

There are so many options out there.

I think the simplest one is HTML5 form validation as described here: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms_in_HTML#HTML_Syntax_for_Constraint_Validation

See example: http://plnkr.co/edit/Uw6fz0Ul8ut5tm6EO4XD?p=preview

<form>
  <input type="email" required>
  <input type="submit">
</form>

在此处输入图片说明


If you need anything more advanced look at some libraries, plenty of results for "JavaScript form validation"... (default HTML5 methods should be enough)

You can try this: First attach a function before it send the form:

onSubmit="javascript: return check_form()" 

And then, use a function like this, for example:

function check_form(){  
    var first_element = document.getElementsByClassName("first_Control");
    var error = 0;
    if(Condition first_Control == false){
        error++;
    }
        if(error != 0){
        return false;
    }
}

Hope this helps you!

If you save the errors to a variable, you can then submit the form via javascript/jquery when you're done logging the errors.

$("#formid").submit();

You just need to remove the

type="submit"

property from the button that submits the form, and get the button to trigger your javascript method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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