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;
}
});
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>
I currently trying to make a website with a validating booking form for a university a project about a university portal. It used to work with my javascript validation until I added to validate time. Problem is sumbit button not working when I add to validate time and whenever I remove it is working.
HTML and JavaScript
/** Validation Form**/
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateID(contact.id);
reason += validateWorkshop(contact.workshop);
reason += validateDate(contact.date);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return true;
}
}
/**Validate name**/
function validateName(name) {
var error = "";
if (name.value.length == 0) {
document.getElementById('name-error').innerHTML = "Please enter your First name.";
var error = "1";
} else {
document.getElementById('name-error').innerHTML = '';
}
return error;
}
/**Validate email as required field and format**/
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value);
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
document.getElementById('email-error').innerHTML = "Please enter your Email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { /**test email for illegal characters**/
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
document.getElementById('email-error').innerHTML = '';
}
return error;
}
/**Validate phone for required and format**/
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter your phone number";
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
} else {
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
/**Validate student ID**/
function validateID(id) {
var error = "";
if (id.value.length == 0) {
document.getElementById('id-error').innerHTML = "Please enter your ID.";
var error = "1";
} else {
document.getElementById('id-error').innerHTML = '';
}
return error;
}
/**Validate workshop select**/
function validateWorkshop(workshop) {
if ((contact.workshop[0].checked == false) && (contact.workshop[1].checked == false) && (contact.workshop[2].checked == false) && (contact.workshop[3].checked == false) && (contact.workshop[4].checked == false) && (contact.workshop[5].checked == false)) {
document.getElementById('workshop-error').innerHTML = "You must select a workshop";
var error = "2";
} else {
document.getElementById('workshop-error').innerHTML = '';
}
return error;
}
/**Validate date**/
function validateDate(date) {
var error = "";
if (date.value.length == 0) {
document.getElementById('date-error').innerHTML = "Please enter a date.";
var error = "1";
} else {
document.getElementById('date-error').innerHTML = '';
}
return error;
}
<header>
<center><img src="portal2.png" style="width:1000px;height:100px;"></center>
<p align="right">
<a href=".pdf" download>
<font color="darkblue">
<font size="5"><b>Report</font></b></a>
</p>
</header>
<hr class="line">
<div class="topnav" id="myTopnav">
Home
Timetable
Book a workshop
Contact
</div>
<br>
<br>
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="thankyou.html" method="post" target="_blank">
<div>
<label><u>First Name:</u></label><br>
<br>
<input type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<br>
<div>
<label><u>Email:</u></label><br>
<br>
<input type="email" name="email" id="email" tabindex="2" autofocus />
<div id="email-error" class="error"></div>
</div>
<br>
<div>
<label><u>Phone:</u></label><br>
<br>
<input type="tel" name="phone" id="phone" tabindex="3" autofocus />
<div id="phone-error" class="error"></div>
</div>
<br>
<div>
<label><u>Student ID:</u></label><br>
<br>
<input type="text" name="id" id="id" tabindex="4" autofocus />
<div id="id-error" class="error"></div>
</div>
<br>
<br>
<div>
<label><u>Please Select a workshop to book:</u></label>
<br>
<br>
<input type="radio" name="workshop" id="art" tabindex="5" autofocus />Art Workshop <br>
<input type="radio" name="workshop" id="computer" tabindex="6" autofocus />Computer Workshop <br>
<input type="radio" name="workshop" id="film" tabindex="7" autofocus />Film Production Workshop <br>
<input type="radio" name="workshop" id="music" tabindex="8" autofocus />Music Performance Workshop <br>
<input type="radio" name="workshop" id="journalism" tabindex="9" autofocus />Journalism Workshop <br>
<input type="radio" name="workshop" id="sociology" tabindex="10" autofocus />Sociology Workshop <br>
<div id="workshop-error" class="error"></div>
</div>
<br>
<p><u>Enter the date you want to book the workshop:</u></p>
<input type="date" name="date" id="date" min="2017-10-01" tabindex="11" autofocus />
<div id="date-error" class="error"></div>
<br>
<br>
<div>
<button type="submit" name="submit" id="submit" tabindex="12">Sumbit</button>
</div>
</form>
<br>
<br>
<footer>University. Copyright © 2015
<br>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
<br>
</footer>
Any suggestions?
You should do this kind of thing with required.
<input type="email" required>
Note: The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
(https://www.w3schools.com/tags/att_input_required.asp)
There also exist pattern. For example, if you want to allow only six letters
<input type="text" pattern="[A-Za-z]{6}" required>
Here's a stackoverflow question that gives more information.
As i can see, the problem isn't on validateDate but on validateWorkshop. If you try to submit a blank form, without choosing a workshop, reason.length gets value 5. But if you pick a workshop, reason.length gets 13.
Not that i recomend your validation but to get this working, i just added a var error = ""; at the begining of validateWorkshop.
/** Validation Form**/
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateID(contact.id);
reason += validateWorkshop(contact.workshop);
reason += validateDate(contact.date);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return true;
}
}
/**Validate name**/
function validateName(name) {
var error = "";
if (name.value.length == 0) {
document.getElementById('name-error').innerHTML = "Please enter your First name.";
var error = "1";
} else {
document.getElementById('name-error').innerHTML = '';
}
return error;
}
/**Validate email as required field and format**/
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value);
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
document.getElementById('email-error').innerHTML = "Please enter your Email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { /**test email for illegal characters**/
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
document.getElementById('email-error').innerHTML = '';
}
return error;
}
/**Validate phone for required and format**/
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter your phone number";
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
} else {
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
/**Validate student ID**/
function validateID(id) {
var error = "";
if (id.value.length == 0) {
document.getElementById('id-error').innerHTML = "Please enter your ID.";
var error = "1";
} else {
document.getElementById('id-error').innerHTML = '';
}
return error;
}
/**Validate workshop select**/
function validateWorkshop(workshop) {
var error = "";
if ((contact.workshop[0].checked == false) && (contact.workshop[1].checked == false) && (contact.workshop[2].checked == false) && (contact.workshop[3].checked == false) && (contact.workshop[4].checked == false) && (contact.workshop[5].checked == false)) {
document.getElementById('workshop-error').innerHTML = "You must select a workshop";
var error = "2";
} else {
document.getElementById('workshop-error').innerHTML = '';
}
return error;
}
/**Validate date**/
function validateDate(date) {
var error = "";
if (date.value.length == 0) {
document.getElementById('date-error').innerHTML = "Please enter a date.";
var error = "1";
} else {
document.getElementById('date-error').innerHTML = '';
}
return error;
}
<header>
<center><img src="portal2.png" style="width:1000px;height:100px;"></center>
<p align="right">
<a href=".pdf" download>
<font color="darkblue">
<font size="5"><b>Report</font></b></a>
</p>
</header>
<hr class="line">
<div class="topnav" id="myTopnav">
Home
Timetable
Book a workshop
Contact
</div>
<br>
<br>
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="thankyou.html" method="post" target="_blank">
<div>
<label><u>First Name:</u></label><br>
<br>
<input type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<br>
<div>
<label><u>Email:</u></label><br>
<br>
<input type="email" name="email" id="email" tabindex="2" autofocus />
<div id="email-error" class="error"></div>
</div>
<br>
<div>
<label><u>Phone:</u></label><br>
<br>
<input type="tel" name="phone" id="phone" tabindex="3" autofocus />
<div id="phone-error" class="error"></div>
</div>
<br>
<div>
<label><u>Student ID:</u></label><br>
<br>
<input type="text" name="id" id="id" tabindex="4" autofocus />
<div id="id-error" class="error"></div>
</div>
<br>
<br>
<div>
<label><u>Please Select a workshop to book:</u></label>
<br>
<br>
<input type="radio" name="workshop" id="art" tabindex="5" autofocus />Art Workshop <br>
<input type="radio" name="workshop" id="computer" tabindex="6" autofocus />Computer Workshop <br>
<input type="radio" name="workshop" id="film" tabindex="7" autofocus />Film Production Workshop <br>
<input type="radio" name="workshop" id="music" tabindex="8" autofocus />Music Performance Workshop <br>
<input type="radio" name="workshop" id="journalism" tabindex="9" autofocus />Journalism Workshop <br>
<input type="radio" name="workshop" id="sociology" tabindex="10" autofocus />Sociology Workshop <br>
<div id="workshop-error" class="error"></div>
</div>
<br>
<p><u>Enter the date you want to book the workshop:</u></p>
<input type="date" name="date" id="date" min="2017-10-01" tabindex="11" autofocus />
<div id="date-error" class="error"></div>
<br>
<br>
<div>
<button type="submit" name="submit" id="submit" tabindex="12">Sumbit</button>
</div>
</form>
<br>
<br>
<footer>University. Copyright © 2015
<br>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
<br>
</footer>
So, I'm currently doing my final internship for the Network Administration training at school. And I've been asked to create a simple web page that allows for selecting a range of servers to perform a clean install on. Like: when I select 'Server 1' and 'Server 4' > click 'Submit' > confirm my action > launch VBscript that performs clean install.
What I have so far (also refer to pieces of code at end):
- Basic welcome text
- Check boxes
- Select all (javascript)
- Continue button
- When clicking continue button > show warning that asks for confirmation
What I want it to do, is launching the script of the selected box(es) after confirming. Is that possible? I mean, I assume I'll need something else than HTML. Javascript maybe? How would I do such thing?
I'm not a total expert with this stuff, not at all. I do have some experience with HTML and CSS, but Javascript and all that? Nope, not at all. Would be very happy to have some help with this!
<html>
<head>
<title>
Huawei Cleaning Center
</title>
<script type="text/javascript">
function SetAllCheckBoxes(FormName, FieldName, CheckValue)
{
if(!document.forms[FormName])
return;
var objCheckBoxes = document.forms[FormName].elements[FieldName];
if(!objCheckBoxes)
return;
var countCheckBoxes = objCheckBoxes.length;
if(!countCheckBoxes)
objCheckBoxes.checked = CheckValue;
else
// set the check value for all check boxes
for(var i = 0; i < countCheckBoxes; i++)
objCheckBoxes[i].checked = CheckValue;
}
</script>
<script type="text/javascript">
function clicked() {
if (confirm('Weet u zeker dat u wilt doorgaan?')) {
yourformelement.submit();
} else {
return false;
}
}
</script>
</head>
<body>
<center><h1>Welkom bij Huawei Cleaning Center!</h1></center>
<br><br>
Kruis één of meerdere van de volgende servers aan waarop u een Clean Install wilt uitvoeren:<br><br>
<form method="GET" action="page17.php" name="myForm" onsubmit="return false;">
<label for="myCheckbox1">
<input type="checkbox" name="myCheckbox" value="1" id="myCheckbox1">
172.16.115.11 </label>
<br>
<label for="myCheckbox2"><input type="checkbox" name="myCheckbox" value="2" id="myCheckbox2">
172.16.115.21 </label>
<br>
<label for="myCheckbox3"><input type="checkbox" name="myCheckbox" value="3" id="myCheckbox3">
172.16.115.31 </label>
<br>
<label for="myCheckbox4"><input type="checkbox" name="myCheckbox" value="4" id="myCheckbox4">
172.16.115.41 </label>
<br><br><input type="submit" id="submit1" onclick="clicked();" value="Doorgaan">
<input type="button" onclick="SetAllCheckBoxes('myForm', 'myCheckbox', true);" value="Selecteer alles">
<input type="button" onclick="SetAllCheckBoxes('myForm', 'myCheckbox', false);" value="Deselecteer alles">
</form>
</body>
</html>
Change your js like this. Form gonna submit if you click yes
<script type="text/javascript">
function clicked() {
var confirmed = confirm('Weet u zeker dat u wilt doorgaan?')
if (confirmed) {
yourformelement.submit();
} else {
alert('You clicked No');
}
}
</script>
if you use JQuery you also could do this:
$(yourformelement).submit(function(e){
var dialogresult = confirm('Confirm');
if (dialogresult ) {
return true;
} else {
return false;
}
});
Looking at your code, it seems like you're using PHP. In this case you could try something like this in your php page (page17.php as referred in the action attribute):
if(!empty($_POST['serverList'])) {
foreach($_POST['serverList'] as $arg) {
exec('cscript "path/to/script.vbs" ' . $arg);
}
}
$_POST['serverList'] contains an array of the checkboxes values and the foraech loop will execute a VBscript passing the values as arguments.
Here's a snippet of the JS/CSS/HTML code:
function setCheckboxes(checkboxName, value) {
checkboxes = document.getElementsByName(checkboxName);
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = value;
}
}
function submitForm(checkboxName) {
checkboxes = document.getElementsByName(checkboxName);
for (var i = 0, n = checkboxes.length; i < n; i++) {
if (checkboxes[i].checked == true) {
confirmation = confirm('Weet u zeker dat u wilt doorgaan?');
if (confirmation) {
return true;
} else {
return false;
}
}
}
alert('No server selected!');
return false;
}
.main-heading {
margin-bottom: 60px;
text-align: center;
}
.info {
margin-bottom: 60px;
}
<h1 class="main-heading">Welkom bij Huawei Cleaning Center!</h1>
<p class="info">
Kruis één of meerdere van de volgende servers aan waarop u een Clean Install wilt uitvoeren:
</p>
<form method="POST" action="page17.php" name="myForm" onsubmit="return false;">
<label for="checkbox-1">
<input type="checkbox" name="serverList[]" value="1" id="checkbox-1">
172.16.115.11
</label>
<br>
<label for="checkbox-2">
<input type="checkbox" name="serverList[]" value="2" id="checkbox-2">
172.16.115.21
</label>
<br>
<label for="checkbox-3">
<input type="checkbox" name="serverList[]" value="3" id="checkbox-3">
172.16.115.31
</label>
<br>
<label for="checkbox-4">
<input type="checkbox" name="serverList[]" value="4" id="checkbox-4">
172.16.115.41
</label>
<br><br>
<input type="submit" onclick="submitForm('serverList[]');" value="Doorgaan">
<input type="button" onclick="setCheckboxes('serverList[]', true);" value="Selecteer alles">
<input type="reset" value="Deselecteer alles">
</form>
Hope it helps :)
Can someone help me make this alert look much nicer? Like Maybe split up Each text box on its own line? I can not figure out how to make this look a lot cleaner and not just all piled on one line.
To see alert hit Lien radio button and then hit next without filling textboxes
http://jsfiddle.net/t4Lgm0n2/9/
function validateForm(){
var QnoText = ['lien']; // add IDs here for questions with optional text input
var ids = '';
flag = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids = QnoText[i]+'lname';
var eD = "";
if (CkStatus && document.getElementById(ids).value == '') {
eD = eD+' lienholder name';
document.getElementById(ids).focus();
flag = false;
}
ids2 = QnoText[i]+'laddress';
if (CkStatus && document.getElementById(ids2).value == '') {
eD=eD+' lienholder address';
document.getElementById(ids2).focus();
flag = false;
}
ids3 = 'datepicker2';
if (CkStatus && document.getElementById(ids3).value == '') {
eD=eD+' lien date';
document.getElementById(ids3).focus();
flag = false;
}
if(eD!="") alert("Please enter "+eD);
}
return flag;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="radio" value="Yes" name="lien" id="lien" required="yes" onchange="showhideForm(this.value);"/><label for="lien">Lien</label>
<input type="radio" value="None" name="lien" id="nolien" onchange="showhideForm(this.value);"/><label for="nolien">No Lien</label>
<script type="text/javascript">
function showhideForm(lien) {
if (lien == "Yes") {
document.getElementById("div1").style.display = 'block';
document.getElementById("div2").style.display = 'none';
}
else if (lien == "None") {
document.getElementById("div2").style.display = 'block';
document.getElementById("div1").style.display = 'none';
$("#div1 > .clearfix input:text").val("");
}
}
</script>
<div id="div1" style="display:none">
<div class="clearfix">
<label for="lname">Lienholder Name:</label>
<input type="text" name="lienlname" validateat="onSubmit" validate="maxlength" id="lienlname" size="54" maxlength="120" message="Please enter lienholder name." value="">
</p>
<p>
<label for="laddress">Lienholder Address:</label>
<input type="text" name="lienladdress" validateat="onSubmit" validate="maxlength" id="lienladdress" size="54" maxlength="120" message="Please enter lienholder address." value="">
</p>
<p>
<label for="ldate">Date of Lien:</label>
<input type="text" name="lienldate" id="datepicker2" mask="99/99/9999" value="">
</div>
</div>
<div id="div2" style="display:none">
<!---You are not qualified to see this form.--->
</div>
<input type="submit" name="submit" value="Next" onclick="validateForm()">
You can use new line characters \n to make text more readable:
var eD = [];
if (CkStatus && document.getElementById(ids).value == '') {
eD.push('Please enter lienholder name');
document.getElementById(ids).focus();
flag = false;
}
// ...
if (eD.length) alert(eD.join('\n'));
As you can see I'm also pushing error messages into ed array, which makes it more convenient to concatenate resulting message using .join() method.
Demo: http://jsfiddle.net/t4Lgm0n2/11/
Anyone knows what is wrong here?
Keep getting 500 Internal Server Error. -
"NetworkError: 500 Internal Server Error - http:// sitename /validationengine.php"
Somehow I guess it's something wrong with the php-code. Everything with the validation works until it's time for the send.
HTML
<form id="competition_form" accept-charset="UTF-8" enctype="multipart/form-data" method="post" name="val_form" action="validationengine.php">
<fieldset>
<div id="page1_form" class="pages_form">
<p>Line1</p><br>
<input type="checkbox" name="quest" class="quest_group" value="1"><span class="nr_checkboxes">1. </span>
<label for="quest">labeltext 1</label><br>
<input type="checkbox" name="quest" class="quest_group" value="x"><span class="nr_checkboxes">X. </span>
<label for="quest">labeltext X</label><br>
<input type="checkbox" name="quest" class="quest_group" value="2"><span class="nr_checkboxes">2. </span>
<label for="quest">labeltext 2</label><br>
<p>Text</p>
<textarea name="motivering" rows="4" cols="66" maxlength="100"></textarea>
</div>
<div id="page2_form" class="pages_form">
<input type="checkbox" name="prize_check" value="win 1">
<label for="prize_check">Win 1</label><br>
<input type="checkbox" name="prize_check" value="win 2">
<label for="prize_check">Win 2</label><br>
<div class="full_input input_blocks">
<label for="namn">Namn:</label>
<input type="text" name="namn" maxlength="100" value="" />
<span id="namn_error" class="error">Du måste skriva in ditt namn.</span>
</div>
<div class="full_input input_blocks">
<label for="adress">Adress:</label>
<input type="text" name="adress" maxlength="100" value="" />
<span id="adress_error" class="error">Du måste skriva in din adress.</span>
</div>
<div class="half_input input_blocks">
<label for="postnr">Postnr:</label>
<input type="text" name="postnr" maxlength="50" value="" />
<span id="postnr_error" class="error">Du måste skriva in ditt postnummer.</span>
</div>
<div class="half_input input_blocks">
<label for="ort">Ort:</label>
<input type="text" name="ort" maxlength="50" value="" />
<span id="ort_error" class="error">Du måste skriva in din bostadsort.</span>
</div>
<div class="half_input input_blocks">
<label for="email">Mejl:</label>
<input type="text" name="email" maxlength="50" value="" />
<span id="email_error" class="error">Du måste skriva in din mejl-adress.</span>
</div>
<div class="half_input input_blocks">
<label for="mobil">Mobil:</label>
<input type="text" name="mobil" maxlength="50" value="" />
<span id="mobil_error" class="error">Du måste skriva in ditt telefonnummer</span>
</div>
<div id="rules_box">
<input type="checkbox" name="rules_check" value="Tävlingsvillkor godkända">
<label for="rules_check">Jag har läst och godkänner <b>tävlingsvillkoren</b></label><br>
<span id="rules_error" class="error">Du måste godkänna tävlingsvillkoren för att tävla.</span>
</div>
<input type="submit" name="submit" value="" class="submit-button" id="submit_btn" />
</div>
</fieldset>
</form>
JS
$(function() {
$('.error').hide();
$("input[name='email']").onchange=function(){$('.error').hide();};
$("input[name='email']").click(function() {
$('.error').hide();
});
$(".submit-button").click(function() {
var form = $('#competition_form');
var name = $("input[name='namn']").val();
var adress = $("input[name='adress']").val();
var postnr = $("input[name='postnr']").val();
var ort = $("input[name='ort']").val();
var email = $("input[name='email']").val();
var mobil = $("input[name='mobil']").val();
var rules = $("input[name='rules_check']").is(':checked');
$('.error').hide();
if (name == "") {
$("#namn_error").show();
return false;
}
if (adress == "") {
$("#adress_error").show();
return false;
}
if (postnr == "") {
$("#postnr_error").show();
return false;
}
if (ort == "") {
$("#ort_error").show();
return false;
}
if (email == "" || !isValidEmailAddress( email ) ) {
$("#email_error").show();
return false;
}
if (mobil == "") {
$("#mobil_error").show();
return false;
}
console.log(rules);
if (!rules) {
$("#rules_error").show();
return false;
}
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
dataType:'html',
success: function(data) {
$('#thankyou_pop').fadeIn(500);
},
error: function(data) {
//AJAX request not completed
}
});
return false;
});
});
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
PHP
<?php
if( isset($_POST) ){
// validation
$validationOK=true;
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');
$EmailTo = "example#example.com";
$Subject = "Nytt Tävlingsbidrag";
$quest = "";
if (isset($_POST['quest'])) {
$answer = Trim(stripslashes($_POST['quest']));
if($answer == 1) {
$quest = "Rätt svar";
} else {
$quest = "Fel svar";
}
}
if($quest == "") {
$quest = "Inget svar";
}
$motivering = Trim(stripslashes($_POST['motivering']));
if ($motivering == "") {
$motivering = "Ingen motivering";
}
$vinst = "";
if (isset($_POST['prize_check'])) {
$win_answer = Trim(stripslashes($_POST['prize_check']));
if ($win_answer == "") {
$vinst = "Ingen vinst vald"
} else {
$vinst = $win_answer;
}
}
$namn = Trim(stripslashes($_POST['namn']));
$adress = Trim(stripslashes($_POST['adress']));
$postnr = Trim(stripslashes($_POST['postnr']));
$ort = Trim(stripslashes($_POST['ort']));
$Email = Trim(stripslashes($_POST['email']));
$mobil = Trim(stripslashes($_POST['mobil']));
$villkor = Trim(stripslashes($_POST['rules_check']));
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
} else {
// prepare email body text
$headers = "Berocca Boost Tävlingsbidrag" . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$Body = "<h3>Nytt Tävlingsbidrag</h3>
<p><strong>Fråga: </strong> {$quest} </p>
<p><strong>Motivering: </strong> {$motivering} </p>
<p><strong>Föredragen vinst: </strong> {$vinst} </p>
<p><strong>Namn: </strong> {$namn} </p>
<p><strong>Adress: </strong> {$adress} </p>
<p><strong>Postnr: </strong> {$postnr} </p>
<p><strong>Ort: </strong> {$ort} </p>
<p><strong>E-mail: </strong> {$Email} </p>
<p><strong>Mobil: </strong> {$mobil} </p>
<p><strong>Villkor accepterade: </strong> {$villkor} </p>
<br>
<p>IP address: {$ipaddress} Date: {$date} Time: {$time}</p>";
// send email
mail($EmailTo, $Subject, $Body, $headers);
}
}
?>
$vinst = "";
if (isset($_POST['prize_check'])) {
$win_answer = Trim(stripslashes($_POST['prize_check']));
if ($win_answer == "") {
$vinst = "Ingen vinst vald" //<====== (Missing semi-colon ";")
} else {
$vinst = $win_answer;
}
}
You have made a typo error. Missed a semicolon.
if ($win_answer == "")
{
$vinst = "Ingen vinst vald"
^^^ // Missing semicolon
}
else
{
$vinst = $win_answer;
}