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>
Related
I’m studying how to work with HTML forms and JavaScript (JS) and I faced a problem:
I wrote the Meta tags (HTML) and used JS elements, events and functions to treat possible user mistakes. The page shows when user follow in mistake and don’t insert the correct information. But, even with these mistakes, when the “submit button” is used, the alert message is not showing. I tried to inspect what’s happening and browser give a message like:
“DevTools failed to load source map: Could not load content for chrome-extension://nllcnknpjnininklegdoijpljgdjkijc/bundles/content.js.map: System error: net::ERR_BLOCKED_BY_CLIENT”.
Here is my code:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>HTML Forms</h2>
<form id="formulario" action="">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="">
<span id="msg-vld-fname" style="color: red; display:none;"></span>
<br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="">
<span id="msg-vld-lname" style="color: red; display:none;"></span>
<br><br>
<label for="lgenre">Genre:</label><br>
<select name="lgenre" id="lgenre">
<option value="select">Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<span id="msg-vld-lgenre" style="color: red; display:none;"></span>
<br><br>
<input type="submit" value="Submit">
</form>
<script src="./index.js"></script>
</body>
</html>
JavaScript
`
//selecionar elementos - aqui entra tudo o que vai ser "mexido", "manipulável"
let form = document.getElementById("formulario");
let fname = document.getElementById("fname");
let lname = document.getElementById("lname");
let lgenre = document.getElementById("lgenre");
let fname_msg = document.getElementById("msg-vld-fname");
let lname_msg = document.getElementById("msg-vld-lname");
let lgenre_msg = document.getElementById("msg-vld-lgenre");
//validar quando usuário sai do campo
fname.onblur = function (event) {
if (event.target.value.length < 3) {
fname_msg.textContent = "Insert at least 3 carachters"; //exibe a mensagem
fname_msg.style.display = 'block'; //exibe um valor na tela
} else {
fname_msg.style.display = 'none'; //faz o valor da tela "sumir".
}
}
//validar quando usuário muda um campo
lgenre.onchange = function (event) {
if (event.target.value == "select") {
lgenre_msg.textContent = "Select a valida atribute."; //exibe a mensagem
lgenre_msg.style.display = 'block'; //exibe um valor na tela
} else {
lgenre_msg.style.display = 'none'; //faz o valor da tela "sumir".
}
}
//validar quando usuário entra em um campo
fname.onfocus = function () {
fname_msg.style.display = 'none';
}
//validar quando usuário envia o formulário
form.onsubimit = function (event){
if (fname.value.length < 3
|| lgenre.value == "selecione") {
alert("please, complete this form correctly after submition");
event.preventDefault();
}
}
`
My expactation is: when the form has mistakes, according to the rules, shows the alert and forbiden the submitoin.
First, you wrote your event property incorrectly as: **onsubimit** instead of **onsubmit**.
But, you are using a submit button, which attempts to send the form data to whatever resource the form element's action attribute is set to and it will attempt to redirect the browser to that location. In your case, you're not submitting data anywhere, so you should be using a regular button with a click event handler.
Also, you really should be using the modern standard for setting up event handlers, which is .addEventListener() instead of event properties like onXyz. See the updated code for the button's click event below.
And the 6 heading elements in HTML (h1...h6) should not be used because of the way they style their text. They are for setting up the structure of the document. As such, you should always start with h1 and then only use h2 if you want to create a sub-section of the h1. If you then don't like the style of the text that the heading element produces, use CSS to modify that instead of changing to a heading style that you like to the look of.
//selecionar elementos - aqui entra tudo o que vai ser "mexido", "manipulável"
// You don't need a reference to the form, you need a reference to the button
let button = document.querySelector("input[type='button']");
let fname = document.getElementById("fname");
let lname = document.getElementById("lname");
let lgenre = document.getElementById("lgenre");
let fname_msg = document.getElementById("msg-vld-fname");
let lname_msg = document.getElementById("msg-vld-lname");
let lgenre_msg = document.getElementById("msg-vld-lgenre");
//validar quando usuário envia o formulário
// You should just use a regular button and set up a click event handler for it
// using the modern, standards-based approach of .addEventListener()
button.addEventListener("click", function (event){
if (fname.value.length < 3
|| lgenre.value == "selecione") {
alert("please, complete this form correctly after submition");
event.preventDefault();
}
});
//validar quando usuário sai do campo
fname.onblur = function (event) {
if (event.target.value.length < 3) {
fname_msg.textContent = "Insert at least 3 carachters"; //exibe a mensagem
fname_msg.style.display = 'block'; //exibe um valor na tela
} else {
fname_msg.style.display = 'none'; //faz o valor da tela "sumir".
}
}
//validar quando usuário muda um campo
lgenre.onchange = function (event) {
if (event.target.value == "select") {
lgenre_msg.textContent = "Select a valida atribute."; //exibe a mensagem
lgenre_msg.style.display = 'block'; //exibe um valor na tela
} else {
lgenre_msg.style.display = 'none'; //faz o valor da tela "sumir".
}
}
//validar quando usuário entra em um campo
fname.onfocus = function () {
fname_msg.style.display = 'none';
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>HTML Forms</h1>
<form id="formulario" action="">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="">
<span id="msg-vld-fname" style="color: red; display:none;"></span>
<br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="">
<span id="msg-vld-lname" style="color: red; display:none;"></span>
<br><br>
<label for="lgenre">Genre:</label><br>
<select name="lgenre" id="lgenre">
<option value="select">Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<span id="msg-vld-lgenre" style="color: red; display:none;"></span>
<br><br>
<input type="button" value="Submit">
</form>
<script src="./index.js"></script>
</body>
</html>
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>
I'm new here at Stack Overflow an I'm also a beginner in programming so please have mercy :)
I'm trying to block with javascript the submission of a multi field form when one or more fields are empty.
Basically, when I submit the form leaving all the fields blank, the error appears only below the first field but nothing happens to the others and the form is sent.
I do apologize in advance as this topic has already been treated several times in other threads but I can't figure out how to make in work.
I'm using the following code (html and js in the same page):
<script type="text/javascript">
function validateForm() {
var a = document.forms["form1"]["nome"].value;
var b = document.forms["form1"]["cognome"].value;
var c = document.forms["form1"]["azienda"].value;
var d = document.forms["form1"]["CF"].value;
var e = document.forms["form1"]["msg"].value;
if (a == ""){
document.getElementById('err_nome').innerHTML += "Il nome è obbligatorio";
return false;}
if (b == ""){
document.getElementById('err_cognome').innerHTML += "Il cognome è obbligatorio";
return false;}
if (c == ""){
document.getElementById('err_azienda').innerHTML += "Il azienda è obbligatorio";
return false;}
if (d == ""){
document.getElementById('err_CF').innerHTML += "Il CF è obbligatorio";
return false;}
if (e == ""){
document.getElementById('err_msg').innerHTML += "Il msg è obbligatorio";
return false;}
}
</script>
<html>
<body>
<?php include ("incl/header.php"); ?>
<div class="menu">
<?php include ("incl/menu.php") ?>
</div>
<div class="column-left">
</div>
<div class="column-center"><br>
<form name="form1" method="post" action="sendmail.php" onsubmit="validateForm()>
<br>
Nome
<input type="text" name="nome">*
<br><span class="error"><div id="err_nome"></div></span><br><br><br>
Cognome
<input type="text" name="cognome">*
<br><span class="error"><div id="err_cognome"></div></span><br><br><br>
Azienda
<input type="text" name="azienda">*
<br><span class="error"><div id="err_azienda"></div></span><br><br><br>
Codice Fiscale
<input type="text" name="CF">*
<br><span class="error"><div id="err_CF"></div></span><br><br><br>
Messaggio
<textarea id="text" name="msg" rows="5" col="40" maxlength="2000"></textarea>*
<br><span class="error"><div id="err_msg"></div></span><br>
<br>
<input type="submit" name="submit" value="submit">
<br><br><br><br><br><br>
</form>
</div>
<div class="column-right">
</div>
<div class="footer">
<?php include "incl/footer.php"; ?>
</div>
</body>
</html>
Many thanks to those of you will help.
Alberto
You have return false; in all your comparisons, that will exit the validateForm() function after the first incorrect field. If you want to validate all fields, keep the result in variable and return it at the end. Like this:
function validateForm() {
var a = document.forms["form1"]["nome"].value;
var b = document.forms["form1"]["cognome"].value;
var c = document.forms["form1"]["azienda"].value;
var d = document.forms["form1"]["CF"].value;
var e = document.forms["form1"]["msg"].value;
var result = true;
if (a == "") {
document.getElementById('err_nome').innerHTML += "Il nome è obbligatorio";
result = result && false;
}
if (b == "") {
document.getElementById('err_cognome').innerHTML += "Il cognome è obbligatorio";
result = result && false;
}
if (c == "") {
document.getElementById('err_azienda').innerHTML += "Il azienda è obbligatorio";
result = result && false;
}
if (d == "") {
document.getElementById('err_CF').innerHTML += "Il CF è obbligatorio";
result = result && false;
}
if (e == "") {
document.getElementById('err_msg').innerHTML += "Il msg è obbligatorio";
result = result && false;
}
return result
}
<html>
<body>
<div class="menu">
</div>
<div class="column-left">
</div>
<div class="column-center"><br>
<form name="form1" method="post" onsubmit="return validateForm()">
<br> Nome
<input type="text" name="nome">*
<br><span class="error"><div id="err_nome"></div></span><br><br><br> Cognome
<input type="text" name="cognome">*
<br><span class="error"><div id="err_cognome"></div></span><br><br><br> Azienda
<input type="text" name="azienda">*
<br><span class="error"><div id="err_azienda"></div></span><br><br><br> Codice Fiscale
<input type="text" name="CF">*
<br><span class="error"><div id="err_CF"></div></span><br><br><br> Messaggio
<textarea id="text" name="msg" rows="5" col="40" maxlength="2000"></textarea>*
<br><span class="error"><div id="err_msg"></div></span><br>
<br>
<input type="submit" name="submit" value="submit">
<br><br><br><br><br><br>
</form>
</div>
<div class="column-right">
</div>
<div class="footer">
</div>
</body>
</html>
I am trying to hide a form based on a button click. Below is my code:
<html>
<head>
<title>Programma per connettersi a un database tramite il linguaggio PHP
</title>
<style>
#mybutton {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: orange;
margin-top: 20px;
}
</style>
</head>
<body>
<button onclick="button()">Inserisci studente</button>
<div id="mybutton">
<div>
<input type="hidden" name="action" value="submit"> Nome Studente:<br>
<input name="Nome" type="text" value="" placeholder="Inserisci il
nome dello studente" size="30" /><br> Cognome Studente:<br>
<input name="Cognome" type="text" value="" placeholder="Inserisci
il cognome dello studente" size="30" /><br> Eta Studente:<br>
<input name="Eta" type="integer" value="" placeholder="Inserisci
l'età dello studente" size="30" /><br>
<input type="submit" name="insert" value="Inserisci" />
</div>
</div>
<br><br><br>
<button onclick="button()">Aggiorna nome</button>
<div id="mybutton">
Inserisci il nome dello studente da modificare nello spazio sottostante
<br>
<div>
<input type="hidden" name="action" value="submit"> Nuovo Nome:<br>
<input name="NewName" type="text" value="" placeholder="Inserisci il
nuovo nome" size="30" /><br> Vecchio Nome:<br>
<input name="OldName" type="text" value="" placeholder="Inserisci il
nome attuale" size="30" /><br>
<input type="submit" name="insert" value="Aggiornare" />
</div>
</div>
<script>
function button() {
var x = document.getElementById('mybutton');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
</script>
</body>
</html>
When the first button is clicked, everything works as expected, but in the second case when I press the button "Aggiorna nome", the form doesn't hide.
Why does the first button work and the second does not?
There are a few issues with the code:
1) Same ID for 2 different elements ('mybutton').
2) The form tags are not closed properly, so the button submit the form.
Here I fixed up your code so it works:
<html>
<head>
<title>Programma per connettersi a un database tramite il linguaggio
PHP</title>
<style>
.mybutton {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: orange;
margin-top:20px;
}
</style>
</head>
<body>
<button data-id="first-div" onclick="button(this)">Inserisci studente</button>
<div id= "first-div" class="mybutton">
<form action = "DatabaseManagerMySQL.php?operation_type = insert" method
= "POST" enctype = "multipart/form-data">
<input type ="hidden" name = "action" value = "submit">
Nome Studente:<br>
<input name = "Nome" type = "text" value = "" placeholder="Inserisci il
nome dello studente" size = "30"/><br>
Cognome Studente:<br>
<input name = "Cognome" type = "text" value = "" placeholder="Inserisci
il cognome dello studente" size = "30"/><br>
Eta Studente:<br>
<input name = "Eta" type = "integer" value = "" placeholder="Inserisci
l'età dello studente" size = "30"/><br>
<input type= "submit" name = "insert" value = "Inserisci"/>
</form>
</div>
<br><br><br>
<button data-id="second-div" onclick = "button(this)">Aggiorna nome</button>
<div id = "second-div" class="mybutton">
Inserisci il nome dello studente da modificare nello spazio sottostante
<br>
<form action = "DatabaseManagerMySQL.php?operation_type = update" method =
"POST" enctype = "multipart/form-data">
<input type ="hidden" name = "action" value = "submit">
Nuovo Nome:<br>
<input name = "NewName" type = "text" value = "" placeholder="Inserisci il
nuovo nome" size = "30"/><br>
Vecchio Nome:<br>
<input name = "OldName" type = "text" value = "" placeholder="Inserisci il
nome attuale" size = "30"/><br>
<input type= "submit" name = "insert" value = "Aggiornare"/>
</form>
</div>
<script>
function button(obj) {
var divId = obj.getAttribute("data-id");
var x = document.getElementById(divId);
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
</script>
</body>
What i did is to use a class instead of an Id for your elements and add the data-id to the button so the JS functions receives the element's id and knows what element should hide or whatever you like to do.
The default behaviour for button elements is to submit the form they are placed in.
To prevent this behaviour, you can add the type="button" attribute to your button. This way your javascript code will be executed.
<button type="button" onclick="button()">Aggiorna nome</button>
Don't use many IDs with same value
https://www.w3.org/TR/html5/dom.html#the-id-attribute The id attribute
specifies its element's unique identifier (ID). The value must be
unique amongst all the IDs in the element's home subtree and must
contain at least one character. The value must not contain any space
characters.
Use class instead.
Check your IDE, it seems that it adds spaces before and after "=" inadequately. I bet there shouldn't be any spaces in "DatabaseManagerMySQL.php?operation_type = insert"
Answer:
You didn't close the first <form> tag, that's why first button (the "Aggiorna nome" one) in that form acts like sumbit button (behaviour by default) and submits to "DatabaseManagerMySQL.php?operation_type = insert"
In your code have some problem
1. you missing </form> // close form tag in both form
2. you use same id in main content div so it will not work
3. you use same id in your javascript function so next form will not work
so need to fixed
so fixed close tag, use 2 id and send this id in onclick button function id name so one function will fixed issue
function button(form_div) {
var x = document.getElementById(form_div);
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
<html>
<head>
<title>Programma per connettersi a un database tramite il linguaggio
PHP</title>
<style>
#mybutton {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: orange;
margin-top: 20px;
}
</style>
</head>
<body>
<button onclick="button('mybutton1')" type="button">Inserisci studente</button>
<div id="mybutton1">
<form action="DatabaseManagerMySQL.php?operation_type = insert" method
="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
Nome Studente:<br>
<input name="Nome" type="text" value="" placeholder="Inserisci il
nome dello studente" size="30"/><br>
Cognome Studente:<br>
<input name="Cognome" type="text" value="" placeholder="Inserisci
il cognome dello studente" size="30"/><br>
Eta Studente:<br>
<input name="Eta" type="integer" value="" placeholder="Inserisci
l'età dello studente" size="30"/><br>
<input type="submit" name="insert" value="Inserisci"/>
</form>
</div>
<br><br><br>
<button onclick="button('mybutton2')" type="button">Aggiorna nome</button>
<div id="mybutton2">
Inserisci il nome dello studente da modificare nello spazio sottostante
<br>
<form action="DatabaseManagerMySQL.php?operation_type = update" method=
"POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
Nuovo Nome:<br>
<input name="NewName" type="text" value="" placeholder="Inserisci il
nuovo nome" size="30"/><br>
Vecchio Nome:<br>
<input name="OldName" type="text" value="" placeholder="Inserisci il
nome attuale" size="30"/><br>
<input type="submit" name="insert" value="Aggiornare"/>
</form>
</div>
</body>
</html>
A quick solution would be to simply create a separate javascript function making sure the Div ids are different. The below code is similar to the one posted but (i) include a new javascript function and (2) new Div ids.
This code enables to have two buttons to hide the divs.
<html>
<head>
<title>Programma per connettersi a un database tramite il linguaggio
PHP</title>
<style>
.mybutton {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: orange;
margin-top:20px;
}
</style>
</head>
<body>
<button onclick="button()">Inserisci studente</button>
<div id= "mybutton" class="mybutton">
<form action = "DatabaseManagerMySQL.php?operation_type = insert" method
= "POST" enctype = "multipart/form-data">
<input type ="hidden" name = "action" value = "submit">
Nome Studente:<br>
<input name = "Nome" type = "text" value = "" placeholder="Inserisci il
nome dello studente" size = "30"/><br>
Cognome Studente:<br>
<input name = "Cognome" type = "text" value = "" placeholder="Inserisci
il cognome dello studente" size = "30"/><br>
Eta Studente:<br>
<input name = "Eta" type = "integer" value = "" placeholder="Inserisci
l'et? dello studente" size = "30"/><br>
<input type= "submit" name = "insert" value = "Inserisci"/>
</div>
<br><br><br>
<button onclick="button2();">Aggiorna nome</button>
<div id = "mybutton2" class="mybutton">
Inserisci il nome dello studente da modificare nello spazio sottostante
<br>
<form action = "DatabaseManagerMySQL.php?operation_type = update" method =
"POST" enctype = "multipart/form-data">
<input type ="hidden" name = "action" value = "submit">
Nuovo Nome:<br>
<input name = "NewName" type = "text" value = "" placeholder="Inserisci il
nuovo nome" size = "30"/><br>
Vecchio Nome:<br>
<input name = "OldName" type = "text" value = "" placeholder="Inserisci il
nome attuale" size = "30"/><br>
<input type= "submit" name = "insert" value = "Aggiornare"/>
</div>
<script>
function button() {
var x = document.getElementById('mybutton');
if (x.style.display === 'none') {
x.style.display = 'block';
}else{
x.style.display = 'none';
}
}
function button2() {
var x = document.getElementById('mybutton2');
if (x.style.display === 'none') {
x.style.display = 'block';
}else{
x.style.display = 'none';
}
}
</script>
</body>
</html>
I have a problem with my JavaScript code.
I've been trying to fix it for a really long time now but since i am a beginner at JavaScript, im kinda lost on my own...
First of all, a hidden message should be showing when you submit the page without filling in any fields. Second, when i click a radio button and check some checkboxes and then submit that, my alarm still goes off for some reason.
I really desperately need help with this, but i have noone to ask except you guys so i really hope you can help me!
Here is are the codes:
HTML
<body>
<div id="case">
<div id="title">
<h1>Anmeldung</h1>
</div>
<div id="formulare">
<form onsubmit="checkPw(this)">
<div id="benutzerdaten">
<h3>Benutzerdaten</h3>
<p id="general_alarm" class="alarm">Bitte füllen Sie alle benötigten Felder aus!</p>
<label for="Benutzername">
<input type="email" name="username" id="username" placeholder="Benutzernamen" required>
<p id="user_alarm" class="alarm">Bitte geben Sie eine gültige E-mail Adresse ein!</p>
<label for="Passwort">
<input type="Password" name="password1" id="first_pw" placeholder="Passwort" required>
<p id="password1_alarm" class="alarm">Das Passwort muss mindestens 9 Zeichen lang sein und muss Gross und Kleinbuchstaben und Sonderzeichen enthalten<br> ( ) [ ] { } ? ! $ % & / = * + ~ , . ; : < > - </p>
<label for="Passwort">
<input type="Password" name="password2" id="second_pw" placeholder="Passwort wiederholen"required>
<p id="password2_alarm" class="alarm">Das eingegebene Passwort stimmt nicht mit dem ersten überein!</p>
</div>
</form>
<form>
<div id="altersgruppe">
<h3>Altersgruppe</h3>
<input type="radio" id="opt1" name="Alter" value="<20"><label id="radio1" for="opt1"> <20</label>
<input type="radio" id="opt2" name="Alter" value="20-39"><label id="radio2" for="opt2"> 20-39</label>
<input type="radio" id="opt3" name="Alter" value="40-60"><label id="radio3" for="opt3"> 40-59</label>
<input type="radio" id="opt4" name="Alter" value=">60"><label id="radio4" for="opt4"> >60</label>
<p id="radio_alarm" class="alarm">Bitte geben Sie ihr Alter an!</p>
</div>
</form>
<form>
<div id="programmiersprache">
<h3>Vorgezogene Programmiersprache</h3>
<h4>Mehrere Auswahlen möglich</h4>
<label for="check1">
<input type="checkbox" name="Programmiersprache" value="C++" id="check1">C++</label>
<label for="check2">
<input type="checkbox" name="Programmiersprache" value="C#" id="check2">C#</label>
<label for="check3">
<input type="checkbox" name="Programmiersprache" value="C" id="check3">C</label>
<label for="check4">
<input type="checkbox" name="Programmiersprache" value="Java" id="check4">Java</label>
<p id="checkbox_alarm" class="alarm">Bitte geben Sie mindestens eine Programmiersprache an!</p>
</div>
</form>
<form>
<div id="betriebssystem">
<h3>Betriebssystem</h3>
<select>
<option value="Windows" name="Betriebssystem">Windows</option>
<option value="Mac OS" name="Betriebssystem">Mac OS</option>
<option value="Linux" name="Betriebssystem">Linux</option>
<p id="option_alarm" class="alarm">Bitte wählen Sie ein Betriebssystem aus!</p>
</select>
</div>
</form>
<div id="reset/submit">
<button type="button" id="reset">Eingaben zurücksetzen</button>
<button type="button" id="submit">Eingaben absenden</button>
</div>
</form>
</div>
</div>
JavaScript
$(document).ready(function(){
//versteckt alarme
$('#password1_alarm').hide();
$('#password2_alarm').hide();
$('#user_alarm').hide();
$('#radio_alarm').hide();
$('#checkbox_alarm').hide();
$('#general_alarm').hide();
//pattern für username und passwort definieren
var username_pattern = /.+#.+[.].+/;
var password_pattern = [/[a-zäöü]+/, /[A-ZÄÖÜ]+/, /[0-9]+/, /[\(\)\[\]\{\}\?\!\$\%\&\/\=\*\+\~\,\.\;\:\<\>\-\_]+/];
//überprüft passwort
function checkPw(password1) {
if (password1.length < 9) {
$("#password1_alarm").show();
} else {
for (var i = 0; i < password_pattern.length; i++) {
if (!password_pattern[i].test(password1)) {
$("password1_alarm").show();
return false;
} else {
$("password1_alarm").hide();
if (password_pattern.length -1 == i) {
return true;
}
}
}
}
};
//überprüft email
function checkUn(username){
if (!username_pattern.test(username)) {
$('#user_alarm').show();
return false;
} else {
$('#user_alarm').hide();
return true;
}
}
$('#first_pw').on("keyup", function(){
var password1 = $("#first_pw").val();
checkPw(password1);
});
// Hier wird direkt bei der Eingabe geprüft ob das zweite Passwortfeld 9 Zeichen lang ist und alle vorgegebenen Zeichen ethält.
$('#second_pw').on("keyup", function(){
var password2 = $("#second_pw").val();
checkPw(password2);
});
// Hier wird direkt bei der Eingabe geprüft ob der Username einer Email entspricht.
$('#username').on("keyup", function(){
var username = $('#username').val();
checkUn(username);
});
$("#submit").click(function(){
var username = $("#username").val();
var first_pw = $("#first_pw").val();
var second_pw = $("#second_pw").val();
var radio = $('input[name=Alter]:checked', '#radio').val();
var country = $(".checkbox:selected").val();
var checkbox = [];
$(".checkbox").each(function(){
if ($(this).prop("checked")) {
checkbox.push($(this).val());
}
});
if (username && first_pw && !second_pw && !radio && !checkbox.length) {
var password1 = $("#first_pw").val();
var username = $('#username').val()
if (checkUn(username) && checkPw(password1)) {
window.location.href = "login.html?username=" + username;
}
} else if (!username && !first_pw && !second_pw) {
$('general_alarm').show();
} else {
$('general_alarm').hide();
var pw_ok = false;
var opt_ok = false;
var chbx_ok = false;
if (first_pw != second_pw) {
$('#password2_alarm').show();
var pw_ok = false;
} else {
$('#password2_alarm').hide();
var pw_ok = true;
var password = $("#first_pw").val();
}
if (!radio) {
$('#radio_alarm').show();
var opt_ok = false;
} else {
$('#radio_alarm').hide();
var opt_ok = true;
}
if (!checkbox.length) {
$('#checkbox_alarm').show();
var chbx_ok = false;
} else {
$('#checkbox_alarm').hide();
var chbx_ok = true;
}
if (checkUn(username) && checkPw(password) && pw_ok && opt_ok && chbx_ok){
window.location.href = "anmeldung.html?username="+username+"&password="+password1+"&radio="+radio+"&checkbox="+checkbox+"&country="+country+"";
}
}
});
$("#reset").click(function(){
if (confirm("Sind Sie sicher das Sie all Ihre Daten zurücksetzen wollen?")) {
document.location.reload(true)
}
});
});
You seem to be doing a lot of unnecessary checks. For example, you're checking usernames and passwords on both 'keyup' and when the user submits the form. I would suggest this: streamline your checks so that you're only testing each field once. I think you're getting into some weird logic flow when you're checking for !checkbox.length several times in the same click event. For example, psuedo code like this might be better:
//simple check username function
function checkUn(username){
if (!username_pattern.test(username)) return false;
}
var $username_ok = false; //plus all other 'ok' bool variables.
$('#username').blur(function(){
//check username
if(CheckUn($(this).val())) $username_ok = true;
//don't need else, since $username_ok is already false at declaration
});
//do same for password (include length check) and all other fields
//then, on submit:
$('#submit').click(function(e){
e.preventDefault();
if(!username_ok && !password_ok && ... ){
//display general alarm here
return false;
}
});