I'm trying to validate a form (it's very simple it just have an input and a button) but my JS code doesn't work.
window.onload = iniciar;
function iniciar() {
document.getElementById("btn").addEventListener('submit', validar);
}
function validaNombre() {
var elemento = document.getElementById("nombre");
if (elemento.value = "") {
alert("por favor verifica el campo nombre");
return false;
} else {
return true;
}
}
function validar(e) {
if (validarNombre()) {
alert("Se envio el elemento");
} else {
e.preventDefault();
}
}
<form action="" method="GET" id="miForm">
<br>
<label>Name*</label><br>
<input type="text" class="b1" id="nombre" maxlength="32" name="name">
<br><br><br>
<input type="submit" id="btn" value="Registrar">
<br>
</form>
The submit event goes with the form, not the button.
You also had a typo in the function name validaNombre. And you have to use == to compare, not =.
window.onload = iniciar;
function iniciar() {
document.getElementById("miForm").addEventListener('submit', validar);
}
function validarNombre() {
var elemento = document.getElementById("nombre");
if (elemento.value == "") {
alert("por favor verifica el campo nombre");
return false;
} else {
return true;
}
}
function validar(e) {
if (validarNombre()) {
alert("Se envio el elemento");
} else {
e.preventDefault();
}
}
<form action="" method="GET" id="miForm">
<br>
<label>Name*</label><br>
<input type="text" class="b1" id="nombre" maxlength="32" name="name">
<br><br><br>
<input type="submit" id="btn" value="Registrar">
<br>
</form>
Related
It seems that my "validate" function is not activating for some reason.
I've tried by to use onsubmit and onclick, as well as tried to use ID in the place of name.
The script is already preloaded on head.
function validar() {
var nome = formulario.nome.value;
var email = formulario.email.value;
var cpf = formulario.cpf.value;
var telefone_fixo = formulario.telefone_fixoe.value;
var telefone_celular = formulario.telefone_celular.value;
var login = formulario.login.value;
var senha = formulario.senha.value;
var rep_senha = formulario.rep_senha.value;
if (nome == "") {
alert("Preencha o campo com seu NOME");
formulario.nome.focus();
return false;
}
if (nome.lenght < 5) {
alert("Digite seu NOME COMPLETO");
formulario.nome.focus();
return false;
}
if (cpf.lenght < 11) {
alert("Digite apenas os números do CPF");
formulario.cpf.focus();
return false;
}
if (telefone_fixo < 10) {
alert("Digite apenas os números do TELEFONE");
formulario.telefone_fixo.focus();
return false;
}
if (telefone_celular < 11) {
alert("Digite apenas os números do CELULAR");
formulario.telefone_celular.focus();
return false;
}
if (senha != rep_senha) {
alert("SENHAS não são iguais");
return false;
}
}
<form id="formulario">
<div>PREENCHA OS CAMPOS COM SEUS DADOS REAIS:</div><br/> Nome:
<br/>
<input type="text" id="nome" name="nome"><br/><br/> Email:
<br/>
<input type="text" id="email" name="email" placeholder="exemplo#exemplo.com"><br/><br/> CPF:
<font size="1">(Digite apenas números)</font><br/>
<!--Função de CSS invadindo o HTML provisoriamente-->
<input type="text" id="cpf" name="cpf" placeholder="000.000.000-00"><br/><br/> Telefone:
<font size="1">(Digite apenas números)</font><br/>
<!--Função de CSS invadindo o HTML provisoriamente²-->
<input type="text" id="telefone_fixo" name="telefone_fixo" placeholder="(00) 0000-0000"><br/><br/> Celular:
<font size="1">(Digite apenas números)</font><br/>
<!--Função de CSS invadindo o HTML provisoriamente³-->
<input type="text" id="telefone_celular" name="telefone_celular" placeholder="(00) 00000-0000"><br/><br/><br/>
<div>ESCOLHA SEU LOGIN E SUA SENHA:</div><br/> Login:
<br/>
<input type="text" id="login" name="login"><br/><br/> Senha:
<br/>
<input type="password" id="senha" name="senha"><br/><br/> Repetir Senha:<br/>
<input type="password" id="rep_senha" name="rep_senha"><br/><br/><br/>
<input type="submit" value="Enviar" onclick="return validar()">
<input type="reset" value="Limpar" name="limpar">
</form>
misspelled length
misspelled fixo
missed .length on phone numbers
you need to attach to the submit handler and use preventDefault if error
function validar(e) {
var formulario = this;
var nome = formulario.nome.value;
var email = formulario.email.value;
var cpf = formulario.cpf.value;
var telefone_fixo = formulario.telefone_fixo.value;
var telefone_celular = formulario.telefone_celular.value;
var login = formulario.login.value;
var senha = formulario.senha.value;
var rep_senha = formulario.rep_senha.value;
var error = false
if (nome == "") {
alert("Preencha o campo com seu NOME");
formulario.nome.focus();
error = true;
}
if (!error && nome.lenght < 5) {
alert("Digite seu NOME COMPLETO");
formulario.nome.focus();
error = true;
}
if (!error && cpf.length < 11) {
alert("Digite apenas os números do CPF");
formulario.cpf.focus();
error = true;
}
if (!error && telefone_fixo.length < 10) {
alert("Digite apenas os números do TELEFONE");
formulario.telefone_fixo.focus();
error = true;
}
if (!error && telefone_celular.length < 11) {
alert("Digite apenas os números do CELULAR");
formulario.telefone_celular.focus();
error = true;
}
if (!error && senha != rep_senha) {
alert("SENHAS não são iguais");
error = true;
}
if (error) e.preventDefault();
}
window.addEventListener("load",function() {
document.getElementById("formulario").addEventListener("submit",validar);
})
<form id="formulario">
<div>PREENCHA OS CAMPOS COM SEUS DADOS REAIS:</div><br/> Nome:
<br/>
<input type="text" id="nome" name="nome"><br/><br/> Email:
<br/>
<input type="text" id="email" name="email" placeholder="exemplo#exemplo.com"><br/><br/> CPF:
<font size="1">(Digite apenas números)</font><br/>
<!--Função de CSS invadindo o HTML provisoriamente-->
<input type="text" id="cpf" name="cpf" placeholder="000.000.000-00"><br/><br/> Telefone:
<font size="1">(Digite apenas números)</font><br/>
<!--Função de CSS invadindo o HTML provisoriamente²-->
<input type="text" id="telefone_fixo" name="telefone_fixo" placeholder="(00) 0000-0000"><br/><br/> Celular:
<font size="1">(Digite apenas números)</font><br/>
<!--Função de CSS invadindo o HTML provisoriamente³-->
<input type="text" id="telefone_celular" name="telefone_celular" placeholder="(00) 00000-0000"><br/><br/><br/>
<div>ESCOLHA SEU LOGIN E SUA SENHA:</div><br/> Login:
<br/>
<input type="text" id="login" name="login"><br/><br/> Senha:
<br/>
<input type="password" id="senha" name="senha"><br/><br/> Repetir Senha:<br/>
<input type="password" id="rep_senha" name="rep_senha"><br/><br/><br/>
<input type="submit" value="Enviar">
<input type="reset" value="Limpar" name="limpar">
</form>
Hello Everyone I want to make sure that in my project once I change the value of a radio button next to it is created / or a textBox is made visible ..
If the radioButton is "(SI)" the textBox is shown
if the radioButton is "(NO") the textBox is dimmed
I am attaching an attempt that I made to generate textBox .. but I do not know how to manage the value of the radioButton ..
PS do not be ruthless, I'm a beginner with JavaScript--
<html>
<head>
<script language="JavaScript" type="text/javascript">
<!--
var num=1;
function accoda(){
if(document.createElement && document.getElementById && document.getElementsByTagName) {
// crea elementi
var oTr=document.createElement("TR");
var oTd1=document.createElement("TD");
var oTd2=document.createElement("TD");
var oField=document.createElement("INPUT");
var oButt=document.createElement("INPUT");
// setta attributi
oField.setAttribute("type","text");
oField.setAttribute("name","testo"+num);
oButt.setAttribute("type","button");
oButt.setAttribute("value","rimuovi");
// setta gestore evento
if(oButt.attachEvent) oButt.attachEvent('onclick',function(e){rimuovi(e);})
else if(oButt.addEventListener) oButt.addEventListener('click',function(e){rimuovi(e);},false)
// appendi al relativo padre
oTd1.appendChild(oField);
oTd2.appendChild(oButt);
oTr.appendChild(oTd1);
oTr.appendChild(oTd2);
document.getElementById('tabella').getElementsByTagName('TBODY')[0].appendChild(oTr);
// incrementa variabile globale
num++
}
}
function rimuovi(e){
if(document.removeChild && document.getElementById && document.getElementsByTagName) {
if(!e) e=window.event;
var srg=(e.target)?e.target:e.srcElement;
// risali al tr del td che contiene l' elemento che ha scatenato l' evento
while(srg.tagName!="TR"){srg=(srg.parentNode)?srg.parentNode:srg.parentElement}
// riferimento al tbody
var tb=document.getElementById('tabella').getElementsByTagName('TBODY')[0];
// rimuovi
tb.removeChild(srg);
}
}
//-->
</script>
</head>
<body>
<form name="modulo">
<input type="button" value="accoda" onclick="accoda()" />
<table border="1" id="tabella">
<tbody>
<tr>
<td><input type="text" name="testo0" /></td><td><input type="button" disabled="disabled" value="rimuovi" /></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
<html>
<body>
<script language="javascript">
function controlla(){
x=document.prova;
if (x.scelta.value=="si"){
window.location.href = '../affidatario.php?idCantiere=<?php echo $idCantiere?>'
return false;
}
if (x.scelta.value=="no"){
alert("Hai risposto no");
window.location.href = '../inserimentoCantiere.php'
return false;
}
}
</script>
<fieldset>
<strong>Vuoi inserire un affidatario?</strong>
<form action="?" method="POST" name="prova" onsubmit="return controlla();">
SI<input type="radio" name="scelta" value="si" /><br />
NO<input type="radio" name="scelta" value="no" /><br />
<button type="submit">INVIA</button>
</form>
</fieldset>
</body>
</html>
Try this
function controlla() {
console.log("oie");
x = document.prova;
if (x.scelta.value == "si") {
window.location.href = '../affidatario.php?idCantiere=608675750'
return false;
}
if (x.scelta.value == "no") {
alert("Hai risposto no");
window.location.href = '../inserimentoCantiere.php'
return false;
}
}
document.querySelectorAll('input[name="scelta"').forEach(function(a) {
a.addEventListener("change", function() {
let textBox = document.getElementById("myInput");
if (textBox) textBox.style.display = this.value === "si" ? "block" : "none";
})
});
<html>
<body>
<fieldset>
<strong>Vuoi inserire un affidatario?</strong>
<form action="?" method="POST" name="prova" onsubmit="return controlla();">
SI<input type="radio" name="scelta" value="si">
<input type="text" id="myInput" style="display: block;"><br>
NO<input type="radio" name="scelta" value="no"><br>
<button type="submit">INVIA</button>
</form>
</fieldset>
</body>
</html>
Change the display to 'none' for the textbox
You could have an if block. Something like
if(document.querySelector('_radiobutton_').checked) { //selecting the radio button with "SI"
document.querySelector('theTextBox').style.display = '' //selecting the textbox
}
Here is a simple example:
let chbxElement = document.getElementById('chckbx');
let textBoxElement = document.getElementById('txtbx');
chbxElement.addEventListener('change', (e) => {
textBoxElement.style.display = e.target.checked ? 'block' : 'none';
});
<input type="checkbox" id="chckbx"/>
<input type="text" id="txtbx" hidden/>
Apart from the placement of the textbox, you could add a textbox with for example an id "myInput" and a default display:none;
Then add an eventlistener to the change event. Then according to the value of the radio button show or hide the textbox.
For example:
document.querySelectorAll('input[name="scelta"]').forEach(function(a) {
a.addEventListener("change", function() {
let textBox = document.getElementById("myInput");
if (textBox) textBox.style.display = this.value === "si" ? "block" : "none";
})
});
<html>
<head>
<script language="JavaScript" type="text/javascript">
<!--
var num = 1;
function accoda() {
if (document.createElement && document.getElementById && document.getElementsByTagName) {
// crea elementi
var oTr = document.createElement("TR");
var oTd1 = document.createElement("TD");
var oTd2 = document.createElement("TD");
var oField = document.createElement("INPUT");
var oButt = document.createElement("INPUT");
// setta attributi
oField.setAttribute("type", "text");
oField.setAttribute("name", "testo" + num);
oButt.setAttribute("type", "button");
oButt.setAttribute("value", "rimuovi");
// setta gestore evento
if (oButt.attachEvent) oButt.attachEvent('onclick', function(e) {
rimuovi(e);
})
else if (oButt.addEventListener) oButt.addEventListener('click', function(e) {
rimuovi(e);
}, false)
// appendi al relativo padre
oTd1.appendChild(oField);
oTd2.appendChild(oButt);
oTr.appendChild(oTd1);
oTr.appendChild(oTd2);
document.getElementById('tabella').getElementsByTagName('TBODY')[0].appendChild(oTr);
// incrementa variabile globale
num++
}
}
function rimuovi(e) {
if (document.removeChild && document.getElementById && document.getElementsByTagName) {
if (!e) e = window.event;
var srg = (e.target) ? e.target : e.srcElement;
// risali al tr del td che contiene l' elemento che ha scatenato l' evento
while (srg.tagName != "TR") {
srg = (srg.parentNode) ? srg.parentNode : srg.parentElement
}
// riferimento al tbody
var tb = document.getElementById('tabella').getElementsByTagName('TBODY')[0];
// rimuovi
tb.removeChild(srg);
}
}
//-->
</script>
</head>
<body>
<form name="modulo">
<input type="button" value="accoda" onclick="accoda()" />
<table border="1" id="tabella">
<tbody>
<tr>
<td><input type="text" name="testo0" /></td>
<td><input type="button" disabled="disabled" value="rimuovi" /></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
<html>
<body>
<fieldset>
<strong>Vuoi inserire un affidatario?</strong>
<form action="?" method="POST" name="prova" onsubmit="return controlla();">
SI<input type="radio" name="scelta" value="si" /><br /> NO
<input type="radio" name="scelta" value="no" /><br />
<input type="text" id="myInput" style="display: none;">
<button type="submit">INVIA</button>
</form>
</fieldset>
<script language="javascript">
function controlla() {
x = document.prova;
if (x.scelta.value == "si") {
window.location.href = '../affidatario.php?idCantiere=<?php echo $idCantiere?>'
return false;
}
if (x.scelta.value == "no") {
alert("Hai risposto no");
window.location.href = '../inserimentoCantiere.php'
return false;
}
}
document.querySelectorAll('input[name="scelta"]').forEach(function(a) {
a.addEventListener("change", function() {
let textBox = document.getElementById("myInput");
if (textBox) textBox.style.display = this.value === "si" ? "block" : "none";
})
});
</script>
</body>
</html>
I'm trying to disable the submit button until all inputs have some data. Right now the button is disabled, but it stays disabled after all inputs are filled in. What am I doing wrong?
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
if ($('input').val().length > 0) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
Here's a modification of your code that checks all the <input> fields, instead of just the first one.
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
// get all input fields except for type='submit'
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
// if it has a value, increment the counter
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
Vanilla JS Solution.
In question selected JavaScript tag.
HTML Form:
<form action="/signup">
<div>
<label for="username">User Name</label>
<input type="text" name="username" required/>
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" />
</div>
<div>
<label for="r_password">Retype Password</label>
<input type="password" name="r_password" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" />
</div>
<input type="submit" value="Signup" disabled="disabled" />
</form>
JavaScript:
var form = document.querySelector('form')
var inputs = document.querySelectorAll('input')
var required_inputs = document.querySelectorAll('input[required]')
var register = document.querySelector('input[type="submit"]')
form.addEventListener('keyup', function(e) {
var disabled = false
inputs.forEach(function(input, index) {
if (input.value === '' || !input.value.replace(/\s/g, '').length) {
disabled = true
}
})
if (disabled) {
register.setAttribute('disabled', 'disabled')
} else {
register.removeAttribute('disabled')
}
})
Some explanation:
In this code we add keyup event on html form and on every keypress check all input fields. If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button.
If you need to disable submit button until all required input fields are filled in - replace:
inputs.forEach(function(input, index) {
with:
required_inputs.forEach(function(input, index) {
where required_inputs is already declared array containing only required input fields.
JSFiddle Demo: https://jsfiddle.net/ydo7L3m7/
You could try using jQuery Validate
http://jqueryvalidation.org/
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
And then do something like the following:
$('#YourFormName').validate({
rules: {
InputName1: {
required: true
},
InputName2: { //etc..
required: true
}
}
});
Refer to the sample here.
In this only input of type="text" has been considered as described in your question.
HTML:
<div>
<form>
<div>
<label>
Name:
<input type="text" name="name">
</label>
</div>
<br>
<div>
<label>
Age:
<input type="text" name="age">
</label>
</div>
<br>
<div>
<input type="submit" value="Submit">
</div>
</form>
</div>
JS:
$(document).ready(function () {
validate();
$('input').on('keyup check', validate);
});
function validate() {
var input = $('input');
var isValid = false;
$.each(input, function (k, v) {
if (v.type != "submit") {
isValid = (k == 0) ?
v.value ? true : false : isValid && v.value ? true : false;
}
if (isValid) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
});
}
Try to modify your function like this :
function validate(){
if ($('input').val() != '') {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
and place some event trigger or something like onkeyup in jquery.But for plain js, it looks like this :
<input type = "text" name = "test" id = "test" onkeyup = "validate();">
Not so sure of this but it might help.
Here is a dynamic code that check all inputs to have data when wants to submit it:
$("form").submit(function(e) {
var error = 0;
$('input').removeClass('error');
$('.require').each(function(index) {
if ($(this).val() == '' || $(this).val() == ' ') {
$(this).addClass('error');
error++;
}
});
if (error > 0) {
//Means if has error:
e.preventDefault();
return false;
} else {
return true;
}
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form>
<form action="google.com">
<input type="text" placeholder="This is input #1" class="require" />
<input type="text" placeholder="This is input #2" class="require" />
<input type="submit" value="submit" />
</form>
</form>
Now you see there is a class called require, you just need to give this class to inputs that have to have value then this function will check if that input has value or not, and if those required inputs are empty Jquery will prevent to submit the form!
Modify your code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
<script>
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
$("input[type=text]").each(function(){
if($(this).val().length > 0)
{
$("input[type=submit]").prop("disabled", false);
}
else
{
$("input[type=submit]").prop("disabled", true);
}
});
}
</script>
function disabledBtn(_className,_btnName) {
var inputsWithValues = 0;
var _f = document.getElementsByClassName(_className);
for(var i=0; i < _f.length; i++) {
if (_f[i].value) {
inputsWithValues += 1;
}
}
if (inputsWithValues == _f.length) {
document.getElementsByName(_btnName)[0].disabled = false;
} else {
document.getElementsByName(_btnName)[0].disabled = true;
}
}
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="submit" value="Join" id="yyyyy" disabled name="fruit">
In this HTML form that I have I would like to warn the user that he has to enter a level in the inputbox, if he clicks the button again I would like to clear off the error message and print it out again. I would like to also add more error messages but anything that I add as an error message appends to the end of the previous message.
function validateForm () {
var msg = ""
, result = true;
if (document.ExamEntry.name.value === "") {
msg = document.createTextNode("You Must Indicate Your Level");
document.getElementById('name-msg').appendChild(msg);
document.getElementById('name-msg').style.color="red";
}
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name">
<span id="name-msg"></span>
<input type="button" name="submit" value="Submit" onclick="validateForm();">
</form>
here's a jsbin
function validateForm () {
var result = true;
if (document.ExamEntry.name.value === "") {
document.getElementById('name-msg').innerHTML= "You Must Indicate Your Level";
document.getElementById('name-msg').style.color="red";
}
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name">
<span id="name-msg"></span>
<input type="button" name="submit" value="Submit" onclick="validateForm();">
</form>
Is this what are you looking for?
function validateForm(){
var result = true;
var msg = "";
if(document.ExamEntry.name.value===""){
msg = document.createTextNode("You Must Indicate Your Level");
var span = document.getElementById('name-msg');
while( span.firstChild ) {
span.removeChild( span.firstChild );
}
span.appendChild(msg)
document.getElementById('name-msg').style.color="red";
} else {
var span = document.getElementById('name-msg');
while( span.firstChild ) {
span.removeChild( span.firstChild );
}
}
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name" /><span id="name-msg"> </span>
<input type="submit" name="submit" value="Submit" onclick="validateForm();" />
</form>
You can clear the html like
function validateForm() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value === "") {
msg = document.createTextNode("You Must Indicate Your Level");
document.getElementById('name-msg').appendChild(msg);
document.getElementById('name-msg').style.color = "red";
} else {
document.getElementById('name-msg').innerHTML = '';
}
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name" /><span id="name-msg"></span>
<input type="button" name="submit" value="Submit" onclick="validateForm();" />
</form>
You may possibly use innerHTML:
function validateForm() {
var msg = "",
result = true;
if (document.ExamEntry.name.value === "") {
msg = "You Must Indicate Your Level";
}
document.getElementById('name-msg').innerHTML = msg;
}
#name-msg {
color: red;
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name">
<span id="name-msg"></span>
<br/>
<input type="button" name="submit" value="Submit" onclick="validateForm();">
</form>
I current use a javascript function on the onsubmit() event of my form to check if all the input are not empty.
This works fine on computer, but on mobile phone, it changes the background color (as I want to do when the input is empty) but it still submits the form !!!
My form :
<form id="formContact" action="envoi-message.php" method="post" class="normal" onsubmit="return valideChamps();">
<div class="ddl">
<span>VOUS ÊTES...</span>
<div class="ddlOption">
<ul>
<li onclick="ddlContact('entreprise')"><span>UNE ENTREPRISE</span></li>
<li onclick="ddlContact('ecole')"><span>UNE ÉCOLE</span></li>
<li onclick="ddlContact('personne')"><span>UNE PERSONNE</span></li>
</ul>
</div>
</div>
<input class="cache" type="text" name="entreprise" placeholder="NOM DE L'ENTREPRISE" />
<input class="cache" type="text" name="ecole" placeholder="NOM DE L'ÉCOLE" />
<input type="text" name="nom" placeholder="VOTRE NOM" />
<input type="email" name="email" placeholder="VOTRE EMAIL" />
<textarea name="message" placeholder="VOTRE MESSAGE" ></textarea>
<input id="btnEnvoi" type="submit" value="Envoyer">
</form>
My function :
function valideChamps(){
var bResult = true;
if ($("input[name*='nom']").val() == "") {
$("input[name*='nom']").addClass("error");
bResult = false;
} else {
$("input[name*='nom']").removeClass("error");
}
if ($("input[name*='email']").val() == "") {
$("input[name*='email']").addClass("error");
bResult = false;
} else {
var regex = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (regex.test($("input[name*='email']").val()) == false ) {
$("input[name*='email']").addClass("error");
bResult = false;
} else {
$("input[name*='email']").removeClass("error");
}
}
if ($("#formContact textarea").val() == ""){
$("#formContact textarea").addClass("error");
bResult = false;
}else {
$("#formContact textarea").removeClass("error");
}
if ($("div.ddl > span").text().contains("entreprise")){
if ($("input[name*='entreprise']").val() == "") {
$("input[name*='entreprise']").addClass("error");
bResult = false;
}else {
$("input[name*='entreprise']").removeClass("error");
}
} else if ($("div.ddl > span").text().contains("école")){
if ($("input[name*='ecole']").val() == "") {
$("input[name*='ecole']").addClass("error");
bResult = false;
}else {
$("input[name*='ecole']").removeClass("error");
}
}
return bResult;
}
Do you have any idea about what is wrong...?
Best regards
Audrey
EDIT : I changed my submit button; I put a with onclick which submits the form if bResut == true
Try registering your submit handler to the form using JS, so you can access the event and call preventDefault() instead of (or in addition to) returning false;
Like so:
document.getElementById('formContact').onsubmit = function(e) {
//your validateChamps stuff goes here
if(!bResult) e.preventDefault();
};
EDIT : I changed my submit button; I put a with onclick which submits the form if bResut == true