1
I have the following problem...
I have this code in JS:
window.addEventListener('DOMContentLoaded', function(){
const regexCharactere = /<li>.[^<* ]+/;
const regexEmail = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;;
const nome = document.getElementsByClassName('nome');
const email = document.getElementsByClassName('email');
const buttonForm = document.getElementsByClassName('buttonForm');
buttonForm.addEventListener('click', (e) => {
alert("testando");
if(!regexEmail.test(email.value) {
alert('Formato do e-mail inválido');
email.focus();
e.preventDefault();
}
if(!regexCharactere.test(nome.value) {
alert('Nome inválido');
nome.focus();
e.preventDefault();
}
});
});
Structure HTML
<form method="POST" action="#">
<label class="left">Nome</label>
<input type="text" class="form-control" name="nome" id="nome" placeholder="Nome">
<label class="left">E-mail</label>
<input type="email" class="form-control" name="email" id="email" placeholder="E-mail">
<label class="left">Telefone/Celular</label>
<input type="tel" class="form-control" name="telefone" id="telfone" placeholder="Telefone/Celular">
<button type="submit" class="waves-effect waves-light cta btn-large btn-solicitar-modal pulse-hover buttonForm"> Solicitar curso </button>
</form>
When I try to inject it into my page no error appears from script
, but does not perform as I expected.
I’ve already done some tests:
- I added the
window
initially to load the script - I changed some fields of my HTML and JS, but still no success
- I tried to apply a
alert
(as shown in the script) to see if it captures, but without success as well. - I changed in the
buttonForm.addEventListener('click', (e) => { /// }
forbuttonForm.addEventListener('submit', (e) => { /// }
but it didn’t work either
What’s wrong with mine script?
Edit: In case I haven’t been clear enough, I’ll make the changes.
Would not be
document.getElementsByClassName('buttonForm')[0]
?– SylvioT
I do not know very well what it is to pick up in the position [0]... But in addition to this form, there are 3 other identical forms on the pages (but in different resolutions)... Well, can you explain to me what [0]?
– Devprogramacao
It would be interesting to place an event of
submit
in the form instead of the button.– SylvioT
So, I changed the button for a form variable... But also nothing is happening: It was like this:
const form = document.forms['marketing'].value;
and thenform.addEventListener('submit', (e) => {});
.– Devprogramacao
What you have most is an error in your script, such as closing
(
ofif
's.– Sam
I don’t quite understand @Sam, can you be clearer? Because I’m establishing a condition there... Thanks for noting the error in the script, but I would like to understand better.
– Devprogramacao