My last post was almost a year ago and I stopped posting since I got to know chatGPT. instead of googling around I can easily ask chatGPT and got the answer that I needed. Furthermore, I learned how to vibe code as well. Therefor I have more reasons to stopped posting. A while ago I remember again the reason why I wrote this blog, it helps me recall the things that I need. I'm such a forgetful person.
Ok, lets start. It's about submiting a HTML form using javascript but it has to be validated before submitted. The code is quite simple. The validation function is a native function from HTMLelement.
with native javascript, it will look like this:
function submitWithValidation(){
var form = document.getElementById('myForm');
if (!form.checkValidity()) {
form.reportValidity();
return; // STOP submit
}
//next logic
form.requestSubmit();
}
If you use JQuery, then the code will look like this:
function submitWithValidation(){
var form = $("#myForm");
if (!form[0].checkValidity()) {
form[0].reportValidity();
return; // STOP submit
}
//next logic
form[0].requestSubmit();
}
Why we need that index if when using the JQuery, because JQuery selector returns JQuery collection / object and we need to reference the first element. Why we have to do that? because theses functions:
- checkValidity()
- reportValidity()
- requestSubmit()
are native javascript function, so it need a DOM element.
document.getElementById() returns a DOM element.
Tidak ada komentar:
Posting Komentar