I not able to validate a multiple step form - I want a validation for each field instead of now it validates sets of fields
My code
function show_next(id, nextid, bar) {
var ele = document.getElementById(id).getElementsByTagName("input");
var error = 0;
for (var i = 0; i < ele.length; i++) {
if (ele[i].type == "text" && ele[i].value == "") {
error++;
}
}
if (error == 0) {
document.getElementById("account_details").style.display = "none";
document.getElementById("user_details").style.display = "none";
document.getElementById("qualification").style.display = "none";
$("#" + nextid).fadeIn();
document.getElementById(bar).style.backgroundColor = "#38610B";
} else {
alert("Fill All The details");
}
}
function show_prev(previd, bar) {
document.getElementById("account_details").style.display = "none";
document.getElementById("user_details").style.display = "none";
document.getElementById("qualification").style.display = "none";
$("#" + previd).fadeIn();
document.getElementById(bar).style.backgroundColor = "#D8D8D8";
}
body {
margin: 0 auto;
padding: 0;
text-align: center;
background-color: #D8D8D8;
}
#wrapper {
width: 995px;
padding: 0px;
margin: 0px auto;
font-family: helvetica;
position: relative;
}
#wrapper .baricon {
display: inline-block;
border-radius: 100%;
padding: 12px;
background-color: #38610B;
color: white;
}
#wrapper .progress_bar {
width: 200px;
height: 5px;
border-radius: 20px;
background-color: #D8D8D8;
display: inline-block;
}
#wrapper form div {
margin-left: 340px;
padding: 10px;
box-sizing: border-box;
width: 300px;
margin-top: 50px;
background-color: #585858;
}
#wrapper form div p {
color: #F2F2F2;
margin: 0px;
margin-top: 10px;
font-weight: bold;
}
#wrapper form div .form_head {
font-size: 22px;
font-weight: bold;
margin-bottom: 30px;
}
#wrapper form div input[type="text"] {
width: 200px;
height: 40px;
padding: 5px;
border-radius: 5px;
border: none;
margin-top: 10px;
}
#wrapper form div input[type="button"],
input[type="submit"] {
width: 80px;
height: 40px;
border-radius: 5px;
border: 2px solid white;
background: none;
color: white;
margin: 5px;
margin-top: 10px;
}
#user_details,
#qualification {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="wrapper">
<br>
<span class='baricon'>1</span>
<span id="bar1" class='progress_bar'></span>
<span class='baricon'>2</span>
<span id="bar2" class='progress_bar'></span>
<span class='baricon'>3</span>
<form method="post" action="">
<div id="account_details">
<p class='form_head'>Account Details</p>
<p>Email Address</p>
<input type="text" placeholder='Email Address'>
<p>Password</p>
<input type="text" placeholder='Password'>
<br>
<input type="button" value="Next" onclick="show_next('account_details','user_details','bar1');">
</div>
<div id="user_details">
<p class='form_head'>User Details</p>
<p>First Name</p>
<input type="text" placeholder='First Name'>
<p>Last Name</p>
<input type="text" placeholder='Last Name'>
<p>Gender</p>
<input type="text" placeholder='Gender'>
<br>
<input type="button" value="Previous" onclick="show_prev('account_details','bar1');">
<input type="button" value="Next" onclick="show_next('user_details','qualification','bar2');">
</div>
<div id="qualification">
<p class='form_head'>Qualification</p>
<p>Qualification</p>
<input type="text" placeholder='Qualification'>
<p>Hobbies</p>
<input type="text" placeholder='Hobbies'>
<br>
<input type="button" value="Previous" onclick="show_prev('user_details','bar2');">
<input type="Submit" value="Submit">
</div>
</form>
</div>
Here is a version that will not go to the next page if there are errors
Let me know what you think
I added two validations. You can change the rest. The code is vastly simplified
function isEmail(str) { // simple email validation
return /(.+)#(.+){2,}\.(.+){2,}/.test($.trim(str));
}
function isEmpty(str) { // test for empty string
return $.trim(str) === "";
}
function validate($div) { // validates any div - will not let you leave the div if error
var $fields = $div.find("input"), hasError = false;
$fields.each(function() {
$(this).removeClass("error")
hasError = this.name=="pword" && isEmpty(this.value);
if (hasError) {
$("#pword").addClass("error").focus();
return false;
}
hasError = this.name=="email" && (isEmpty(this.value) || !isEmail(this.value));
if (hasError) {
$("#email").addClass("error").focus();
return false;
}
hasError = isEmpty(this.value); // the rest of the fields
if (hasError) {
$(this).addClass("error").focus();
return false;
}
})
return hasError?false:true;
}
$(function() {
// validate all divs on submit, but actually only necessary to validate thediv the submit is on
$("#myForm").on("submit",function(e) {
$(".page").each(function() {
if (!validate($(this))) {
e.preventDefault(); // stop submission
return false;
}
});
});
$(".nav").on("click", function() {
var $parent = $(this).closest("div");
var $nextDiv = $(this).hasClass("next") ? $parent.next() : $parent.prev();
if (validate($parent)) { // is the div this button is on valid?
$parent.fadeOut(function() { // fade it out and fade the next one in
if ($nextDiv.length) {
$nextDiv.fadeIn()
for (var i=$(".page").length;i> $nextDiv.index(); i--) {
$("#bar" + i).css({"background-color": "#D8D8D8"}); // we are going backwards
}
$("#bar" + $nextDiv.index()).css({"background-color": "#38610B"});
}
});
}
});
});
body {
margin: 0 auto;
padding: 0;
text-align: center;
background-color: #D8D8D8;
}
#wrapper {
width: 995px;
padding: 0px;
margin: 0px auto;
font-family: helvetica;
position: relative;
}
#wrapper .baricon {
display: inline-block;
border-radius: 100%;
padding: 12px;
background-color: #38610B;
color: white;
}
#wrapper .progress_bar {
width: 200px;
height: 5px;
border-radius: 20px;
background-color: #D8D8D8;
display: inline-block;
}
#wrapper form div {
margin-left: 340px;
padding: 10px;
box-sizing: border-box;
width: 300px;
margin-top: 50px;
background-color: #585858;
}
#wrapper form div p {
color: #F2F2F2;
margin: 0px;
margin-top: 10px;
font-weight: bold;
}
#wrapper form div .form_head {
font-size: 22px;
font-weight: bold;
margin-bottom: 30px;
}
#wrapper form div input[type="text"] {
width: 200px;
height: 40px;
padding: 5px;
border-radius: 5px;
border: none;
margin-top: 10px;
}
#wrapper form div input[type="button"],
input[type="submit"] {
width: 80px;
height: 40px;
border-radius: 5px;
border: 2px solid white;
background: none;
color: white;
margin: 5px;
margin-top: 10px;
}
#user_details,
#qualification {
display: none;
}
.error { background-color:pink !important}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="wrapper">
<br>
<span class='baricon'>1</span>
<span id="bar1" class='progress_bar'> </span>
<span class='baricon'>2</span>
<span id="bar2" class='progress_bar'> </span>
<span class='baricon'>3</span>
<form method="post" action="" id="myForm">
<div id="account_details" class="page">
<p class='form_head'>Account Details</p>
<p>Email Address</p>
<input type="text" name="email" id="email" placeholder='Email Address'>
<p>Password</p>
<input type="text" name="pword" id="pword" placeholder='Password'>
<br>
<input type="button" value="Next" class="nav next" />
</div>
<div id="user_details" class="page">
<p class='form_head'>User Details</p>
<p>First Name</p>
<input type="text" name="fname" id="fname" placeholder='First Name'>
<p>Last Name</p>
<input type="text" name="lname" is="lname" placeholder='Last Name'>
<p>Gender</p>
<input type="text" name="gender" id="gender" placeholder='Gender'>
<br>
<input type="button" value="Prev" class="nav prev" />
<input type="button" value="Next" class="nav next" />
</div>
<div id="qualification" class="page">
<p class='form_head'>Qualification</p>
<p>Qualification</p>
<input type="text" placeholder='Qualification'>
<p>Hobbies</p>
<input type="text" placeholder='Hobbies'>
<br>
<input type="button" value="Prev" class="nav prev" />
<input type="Submit" value="Submit">
</div>
</form>
</div>
Related
I have a form with a disabled button at first and if you leave an input empty or fill it with anything but numbers it will raise an error and if you insert number the error will be removed. My question is how can I remove disable attribute from the button after all inputs are error free.
Here what I've tried so far:
$("input").blur(function () {
if (!Number($(this).val()) || $(this).val() === "") {
$(this).addClass("raise-error");
} else {
$(this).removeClass("raise-error");
}
});
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
font-family: "Montserrat", sans-serif;
scroll-behavior: smooth;
text-align: center;
overflow-x: hidden;
color: #08085c;
background-color: #111;
}
.container {
width: 80%;
height: 50vh;
background-color: #fff;
margin: auto;
display: flex;
}
.team {
width: 50%;
height: 100%;
display: flex;
flex-direction: column;
gap: 10px;
justify-content: center;
align-items: center;
}
.team-a {
background-color: bisque;
}
.error {
text-align: right;
color: red;
opacity: 0;
}
.raise-error + .error {
opacity: 1;
}
input.raise-error {
border: 1px solid red;
}
.record-box {
margin-top: 20px;
}
label {
margin-right: 10px;
}
.btn {
margin-top: 20px;
padding: 10px 20px;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="team team-a">
<h2>Team A Records</h2>
<div class="record-box">
<div class="input-field">
<label for="record-1"> Record 1</label>
<input type="text" id="record-1" />
<div class="error">number please</div>
</div>
<div class="input-field">
<label for="record-2"> Record 2</label>
<input type="text" id="record-2" />
<div class="error">number please</div>
</div>
<div class="input-field">
<label for="record-3"> Record 3</label>
<input type="text" id="record-3" />
<div class="error">number please</div>
</div>
</div>
</div>
<button class="btn" disabled>Submit</button>
You can give the inputs a default attribute like data-valid="false".
When a field is blurred, you can change the attribute's value to true after successfully validating it.
You can then enable the button if all the data-valid="false" are changed to data-valid="true"
Try this
$("input").blur(function() {
if (!Number($(this).val()) || $(this).val() === "") {
$(this).addClass("raise-error");
$(this).attr('data-valid', 'false');
} else {
$(this).removeClass("raise-error");
$(this).attr('data-valid', 'true');
}
$('.btn')[$('[data-valid="false"]').length > 0 ? 'attr' : 'removeAttr']('disabled', 'disabled');
});
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
font-family: "Montserrat", sans-serif;
scroll-behavior: smooth;
text-align: center;
overflow-x: hidden;
color: #08085c;
background-color: #111;
}
.container {
width: 80%;
height: 50vh;
background-color: #fff;
margin: auto;
display: flex;
}
.team {
width: 50%;
height: 100%;
display: flex;
flex-direction: column;
gap: 10px;
justify-content: center;
align-items: center;
}
.team-a {
background-color: bisque;
}
.error {
text-align: right;
color: red;
opacity: 0;
}
.raise-error+.error {
opacity: 1;
}
input.raise-error {
border: 1px solid red;
}
.record-box {
margin-top: 20px;
}
label {
margin-right: 10px;
}
.btn {
margin-top: 20px;
padding: 10px 20px;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="some-container">
<div class="team team-a">
<h2>Team A Records</h2>
<div class="record-box">
<div class="input-field">
<label for="record-1"> Record 1</label>
<input type="text" id="record-1" data-valid="false" />
<div class="error">number please</div>
</div>
<div class="input-field">
<label for="record-2"> Record 2</label>
<input type="text" id="record-2" data-valid="false" />
<div class="error">number please</div>
</div>
<div class="input-field">
<label for="record-3"> Record 3</label>
<input type="text" id="record-3" data-valid="false" />
<div class="error">number please</div>
</div>
</div>
</div>
<button class="btn" disabled>Submit</button>
</div>
The most straight forward way and safest is to reuse your validation function for testing both if the input is valid, and testing if all inputs are valid.
The example below puts the inputs where blur is attached to in the allInputs variable, and the button is disabled if not all inputs are valid (with the every function calling the same isValid functionality)
const allInputs = $("input").blur(function () {
const isValid = val => val !== "" && Number(val);
$(this).toggleClass("raise-error",!isValid(this.value));
$('.btn')[0].disabled = !allInputs.toArray().every(i=>isValid(i.value));
});
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
font-family: "Montserrat", sans-serif;
scroll-behavior: smooth;
text-align: center;
overflow-x: hidden;
color: #08085c;
background-color: #111;
}
.container {
width: 80%;
height: 50vh;
background-color: #fff;
margin: auto;
display: flex;
}
.team {
width: 50%;
height: 100%;
display: flex;
flex-direction: column;
gap: 10px;
justify-content: center;
align-items: center;
}
.team-a {
background-color: bisque;
}
.error {
text-align: right;
color: red;
opacity: 0;
}
.raise-error + .error {
opacity: 1;
}
input.raise-error {
border: 1px solid red;
}
.record-box {
margin-top: 20px;
}
label {
margin-right: 10px;
}
.btn {
margin-top: 20px;
padding: 10px 20px;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="team team-a">
<h2>Team A Records</h2>
<div class="record-box">
<div class="input-field">
<label for="record-1"> Record 1</label>
<input type="text" id="record-1" />
<div class="error">number please</div>
</div>
<div class="input-field">
<label for="record-2"> Record 2</label>
<input type="text" id="record-2" />
<div class="error">number please</div>
</div>
<div class="input-field">
<label for="record-3"> Record 3</label>
<input type="text" id="record-3" />
<div class="error">number please</div>
</div>
</div>
</div>
<button class="btn" disabled>Submit</button>
If below code doesn't work:
if ($('.raise-error').length > 0) {
$('.btn').attr( 'disabled', true );
return true;
}
Then please try to change the button tag with:
<input type="button" class="btn">
So I am trying to do this thing where a legend tag shows when the input box is being clicked. The idea is there is that the input box is inside a fieldset and the legend as a hidden class first. If the input box is on focus or clicked, the hidden class will be removed and it will show like this
I also added a part wherein if was left blank the legend tag will disappear by re-adding the removed
hidden class. However, it also leaves awkward whitespace in a place where it is formerly was like this
Did I do something wrong? Is there something I must do first?
The code is here:
$(function() {
$(".next").click(function() {
var div = $(this).closest('.wrapper');
var next = $(this).closest('.wrapper').next();
div.addClass('hidden');
next.removeClass('hidden');
})
})
$(function() {
$('input').click(function() {
$('input').each(function(index) {
const legend = $(this).closest('fieldset').children('legend');
if (($(this).val() == "" || $(this).val() == " ") && $(this).is(":focus") == false) {
if (legend.hasClass('hidden') == false) {
legend.addClass('hidden');
$(this).css("margin-top", "10px");
}
} else {
legend.removeClass('hidden');
$(this).css("margin-top", "-150%");
}
})
})
})
#import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
#import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght#700&display=swap');
html {
font-family: "Poppins", sans-serif;
margin: 0px;
padding: 0px;
background: #EDE9E8;
}
.cover {
width: 100%;
height: 100%;
position: absolute;
}
form {
/*border: 3px solid red;/**/
width: 57%;
height: 100%;
margin: 0 auto;
}
.child {
width: 50%;
}
.wrapper {
background: white;
width: 95%;
height: 65%;
padding: 3%;
margin-top: 8%;
border-radius: 50px;
display: flex;
}
.border_none {
border: none;
}
.border_black {
border: 2px solid black;
}
.with_image {
text-align: center;
margin-top: 15%;
}
.with_image img {
width: 40%;
}
.input_box {
height: 40px;
width: 70%;
}
.wrapper h1 {
margin-top: 10%;
}
.wrapper label {
font-size: 150%;
}
legend {
font-size: 12px;
/*border: 2px solid black;/**/
}
.wrapper fieldset input[type="text"],
.wrapper fieldset input[type="email"],
.wrapper input[type="password"],
input[type="number"] {
width: 100 %;
height: 100 %;
margin - top: 10 px;
border: none;
/**/
}
.wrapper fieldset input[type="text"]: focus,
.wrapper input[type="email"]: focus,
.wrapper input[type="password"]: focus,
input[type="number"]: focus {
outline: none;
}
.child fieldset {
overflow: hidden;
border - radius: 20 px;
}
.wrapper select {
margin - left: 14 %;
height: 40 px;
}
.wrapper.next {
background: #2c54db;
width: 15%;
height: 8%;
border: white;
color: white;
float: right;
border-radius: 40px;
font-weight: bold;
}
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cover">
<form method="post" action="">
<fieldset class="wrapper border_none">
<div class="child">
<h1>Identity</h1>
<fieldset class="input_box" class="input_outer">
<legend class="input_tag hidden">First Name</legend>
<input class="input_inner" type="text" name="fname" placeholder="First Name">
</fieldset><br>
<fieldset class="input_box" class="input_outer">
<legend class="input_tag hidden">Last Name</legend>
<input class="input_inner" type="text" name="lname" placeholder="Last Name">
</fieldset><br>
<label>Civil Status</label>
<select name="civil_status" id="cv_stat">
<option value="Single">Single</option>
<option value="Married">Married</option>
<option value="Widowed">Widowed</option>
<option value="Annulled">Anulled</option>
</select><br><br>
<fieldset class="input_box" class="input_outer">
<legend class="input_tag hidden">Email</legend><input type="email" name="email" placeholder="Email">
</fieldset>
<button type="button" class="next">
Next
</button>
</div>
<div class="child with_image">
<img src="../images/registration/user_folder_125px.png">
</div>
</fieldset>
<fieldset class="wrapper hidden">
<div class="child">
<h1>Password</h1>
<fieldset class="input_box" class="input_outer">
<legend class="input_tag hidden">Password</legend>
<input type="password" name="password" placeholder="Password">
</fieldset>
<br>
<fieldset class="input_box" class="input_outer">
<legend class="input_tag hidden">Confirm Password</legend>
<input type="password" name="cpassword" placeholder="Confirm Password">
</fieldset>
<button type="button" class="next">
Next
</button>
</div>
</div>
<div class="child">
</fieldset>
</form>
</div>
Thank you in advance!
Inside my form the email input box displays a green circle x when the email inside is correct.
I would like it to display a green check mark circle icon like the input boxes above (first name & last name).
In addition, the phone input box displays a red circle check mark icon when the number is invalid and I would like it to display a red circle x icon instead.
If anyone knows how to achieve this your help is appreciated!
Incorrect fa fa icon displaying on email and phone number:
JSFiddle
HTML:
<form class="container" action="https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST">
<label>First Name
<input id="first_name" maxlength="40" name="first_name" size="20" type="text" onkeyup="test()" required><i class="fa fa-check-circle" aria-hidden="true"></i>
</label>
<label>Last Name
<input id="last_name" maxlength="80" name="last_name" size="20" type="text" onkeyup="test()"><i class="fa fa-check-circle" aria-hidden="true"></i>
</label>
<label>Email
<span class="error">Please enter a valid email address</span>
<input id="email" maxlength="80" name="email" size="20" type="text" onkeyup="test()"><i class="fa fa-times-circle-o" aria-hidden="true"></i>
</label>
<label>Phone
<span class="error">Please enter a valid phone number</span>
<input id="phone" maxlength="80" name="phone" size="20" type="tel" onkeyup="test()"><i class="fa fa-check-circle" aria-hidden="true"></i>
</label>
<label>City
<input id="city" name="city" maxlength="40" size="20" type="text" onkeyup="test()"><i class="fa fa-check-circle" aria-hidden="true"></i>
</label>
<label>State/Province
<input id="state" maxlength="20" name="state" size="20" type="text" onkeyup="test()"><i class="fa fa-check-circle" aria-hidden="true"></i>
</label>
<label id="co">Company
<input id="company" name="company" type="text" onkeyup="test()"><i class="fa fa-check-circle" aria-hidden="true"></i>
</label>
<label>Comments
<textarea id="comments" name="" id="" cols="30" rows="10" onkeyup="test()"></textarea>
<input id="sub" type="submit" disabled="disabled" />
</label>
<div>
<select hidden="true" id="00N6A000008yXMN" name="00N6A000008yXMN" title="Product Interest">
<option value="">--None--</option>
<option selected="selected" value="Visiant">Visiant</option>
<option value="Tessellate">Tessellate</option>
</select><br>
<select hidden="true" id="lead_source" name="lead_source">
<option value="">--None--</option>
<option value="Internal">Internal</option>
<option value="Trade Show">Trade Show</option>
<option selected="selected" value="Website">Website</option>
<option value="Direct Marketing">Direct Marketing</option>
<option value="Social Media">Social Media</option>
<option value="Other">Other</option>
</select><br>
</div>
</form>
CSS:
body {
color: #fff;
background-color: #f78e2a;
text-align: center;
}
form {
color: #fff;
background-color: #f78e2a;
text-align: center;
font-family: Lato;
}
* {
box-sizing: border-box;
}
.form-title {
font-size: 38px;
color: #fff;
font-family: "Lato";
letter-spacing: 70px;
}
input[type="tel"] {
width: 100%;
height: 85%;
padding: 10px;
background-color: #f9a558;
border: 1px solid #fff;
}
input[type="text"] {
width: 100%;
padding: 10px;
background-color: #f9a558;
border: 1px solid #fff;
}
input[type="text"]:focus {
background-color: #fff;
}
input[type="text"]:visited {
background-color: #fff;
}
input[type="tel"]:focus {
background-color: #fff;
}
input[type="tel"]:visited {
background-color: #fff;
}
.container {
display: flex;
flex-direction: column;
padding: 5px 0;
margin-left: 10%;
margin-right: 10%;
}
textarea {
width: 100%;
background-color: #f9a558;
border: 1px solid #fff;
}
textarea:focus {
background-color: #fff;
}
#co {
flex-basis: 100%;
max-width: 100%;
}
label:nth-last-child(-n+2) {
flex-basis: 100%;
max-width: 100%;
}
select,
label {
height: 50px;
width: 48%;
margin: 2% 1%;
text-align: left;
font-family: "Lato";
}
#sub {
border-radius: 6px;
width: 120px;
height: 35px;
text-transform: uppercase;
display: block;
margin-top: 10px;
}
button {
margin-top: 10px;
background-color: #B9B9B9;
color: #959595;
border-radius: 6px;
width: 120px;
height: 35px;
margin-left: 1%;
display: block;
}
button:focus {
background-color: #fff;
color: #f78e2a;
}
#media (max-width: 426px) {
label {
width: 98%;
}
}
#media (min-width: 426px) {
.container {
flex-direction: row;
flex-wrap: wrap;
align-self: flex-start;
}
}
label {
position: relative;
}
.fa {
position: absolute;
bottom: 0;
right: 0;
transform: translate(-50%, -5%);
opacity: 0;
transition: opacity .5s, color .5s;
}
[data-valid] .fa {
opacity: 1;
color: green;
}
[data-valid="valid"] .fa {
color: green;
}
[data-valid="error"] .fa {
color: red;
}
.error {
display: none;
color: red;
font-size: .7em;
position: absolute;
left: 10px;
top: 0;
transform: translateY(150%);
}
[data-valid="error"] .error {
display: block;
}
jQuery:
function phoneNumber(phone) {
var phoneno = /^\d{9}|\d{10}|\d{11}$/;
return phoneno.test(phone);
}
$('input[type="tel"]').on('keyup', function() {
var $label = $(this).closest('label');
if ($(this).val().trim() != '') {
if ($(this).is('#phone')) {
if (phoneNumber($(this).val())) {
$label.attr('data-valid', 'valid');
} else {
$label.attr('data-valid', 'error');
console.log("this works")
}
} else {
$label.attr('data-valid', 'valid');
console.log("this works")
}
} else {
$label.removeAttr('data-valid');
console.log("this works")
}
});
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\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,}))$/;
return re.test(email);
}
$('input[type="text"]').on('keyup', function() {
var $label = $(this).closest('label');
if ($(this).val().trim() != '') {
if ($(this).is('#email')) {
if (validateEmail($(this).val())) {
$label.attr('data-valid', 'valid');
} else {
$label.attr('data-valid', 'error');
console.log("this works")
}
} else {
$label.attr('data-valid', 'valid');
console.log("this works")
}
} else {
$label.removeAttr('data-valid');
console.log("this works")
}
});
test = function() {
if ($("#first_name").val() && $("#last_name").val() && $("#email").val() && $("#phone").val() && $("#city").val() && $("#state").val() && $("#company").val()) {
$("#sub").removeAttr("disabled");
}
}
Your script is working...
But you just dont change the FA icon depending on the validation result.
If valid, add:
$(this).next("i").removeClass("fa-times-circle-o").addClass("fa-check-circle");
If error, add:
$(this).next("i").removeClass("fa-check-circle").addClass("fa-times-circle-o");
CodePen
Me and a couple other guys are trying to create a simple blackjack game using javascript for school, but we are having trouble getting it to work correctly. Right now, when new game is clicked, it generates the numbers just fine and the Dealer 2 input is hidden like it should be. However, we are having trouble getting it to where when the Stand button is clicked, the Dealer 2 input becomes visible. Is there a clean way to go about this?
The Code:
<!DOCTYPE html>
<html>
<head>
<title>Simple Blackjack</title>
<meta charset="utf-8">
<style>
body {
font-family: Arial;
background: url("cards.jpg");
}
section {
width: 600px;
height: 300px;
margin: auto;
background-color: #007929;
padding: 15px;
border-radius: 10px;
border: solid #000 2px;
}
header {
width: 550px;
height: 50px;
margin: auto;
margin-bottom: 15px;
background: url("cards.jpg");
text-align: center;
border-radius: 10px;
border: solid #000 1px;
}
h1 {
line-height: 10px;
}
div {
width: 400px;
height: 300px;
float: left;
}
aside {
width: 200px;
height: 300px;
float: right;
}
table {
width: 400px;
font-weight: bold;
color: #fff;
}
.cards {
background-color: #63dd8d;
border: solid #000 1px;
border-radius: 5px;
font-size: 14pt;
padding: 5px;
}
.button {
background-color: #009900;
width: 150px;
color: #fff;
font-weight: bold;
padding: 5px;
border-radius: 5px;
border: solid #000 1px;
clear: both;
margin: bottom: 15px;
}
</style>
<script>
var dealer1;
var dealer2;
var player;
function dealer() {
dealer1 = document.getElementById("dealer1").value = Math.random()*11 + 1;
document.getElementById("dealer1").value = Math.floor(dealer1);
dealer2 = document.getElementById("dealer2").value = Math.random()*11 + 1;
dealer2 = Math.floor(dealer2);
document.getElementById("dealer2").value = "Hidden";
player = document.getElementById("player").value = Math.random()*21 + 2;
document.getElementById("player").value = Math.floor(player);
}
function stand() {
}
function dealCard() {
}
</script>
</head>
<body>
<section>
<header>
<h1>Simple Blackjack</h1>
</header>
<form>
<div>
<table>
<tr>
<td>Dealer Cards:</td>
<td><input id="dealer1" class="cards" type="text" name="dealer1" size="5" disabled="true" /> <input id="dealer2" class="cards" type="text" name="dealer2" size="5" disabled="true" /></td>
</tr>
<tr>
<td>Your Card Total:</td>
<td><input id="player" class="cards" type="text" name="player" size="5" disabled="true" /></td>
</tr>
</table>
</div>
<aside>
<input type="button" name="deal" value="Deal Card" onclick="dealCard()" class="button" /><br><br>
<input type="button" name="stand" value="Stand" onclick="stand()" class="button" /><br><br>
<input type="button" name="newGame" value="New Game" onclick="dealer()" class="button" />
</aside>
</form>
</section>
</body>
</html>
tl;dr
Set the hidden attribute using setAttribute(). Use .removeAttribute() to reverse the setting of the attribute:
function dealer() {
//...set dealer1, dealer2
//hide the element
document.getElementById("dealer2").setAttribute("hidden", "true");
}
function stand() {
//show the element
document.getElementById("dealer2").removeAttribute("hidden");
Is there a clean way to go about this?
Yes, there are multiple. See the explanations below for a few common techniques.
Hidden Attribute
One approach is to set the hidden attribute using setAttribute(). Use .removeAttribute() to reverse the setting of the attribute:
function dealer() {
//...set dealer1, dealer2
//hide the element
document.getElementById("dealer2").setAttribute("hidden", "true");
}
function stand() {
//show the element
document.getElementById("dealer2").removeAttribute("hidden");
There are varying opinions as to which approach is better. Refer to the comments on this blog post, as well as answers like this.
Also note that because the button labeled stand has the name attribute set, there is a reference to it in the DOM via window.stand. Because of this, the function stand() is being replaced with an object pointing to that element. One way to workaround this is to rename the element, like standButton:
<input type="button" name="standButton" value="Stand" onclick="stand()" class="button" />
var dealer1;
var dealer2;
var player;
function dealer() {
dealer1 = document.getElementById("dealer1").value = Math.random() * 11 + 1;
document.getElementById("dealer1").value = Math.floor(dealer1);
dealer2 = document.getElementById("dealer2").value = Math.random() * 11 + 1;
dealer2 = Math.floor(dealer2);
document.getElementById("dealer2").setAttribute("hidden", "true");
player = document.getElementById("player").value = Math.random() * 21 + 2;
document.getElementById("player").value = Math.floor(player);
}
function stand() {
document.getElementById("dealer2").removeAttribute("hidden");
}
function dealCard() {
}
body {
font-family: Arial;
}
section {
width: 600px;
height: 300px;
margin: auto;
background-color: #007929;
padding: 15px;
border-radius: 10px;
border: solid #000 2px;
}
header {
width: 550px;
height: 50px;
margin: auto;
margin-bottom: 15px;
text-align: center;
border-radius: 10px;
border: solid #000 1px;
}
h1 {
line-height: 10px;
}
div {
width: 400px;
height: 300px;
float: left;
}
aside {
width: 200px;
height: 300px;
float: right;
}
table {
width: 400px;
font-weight: bold;
color: #fff;
}
.cards {
background-color: #63dd8d;
border: solid #000 1px;
border-radius: 5px;
font-size: 14pt;
padding: 5px;
}
.button {
background-color: #009900;
width: 150px;
color: #fff;
font-weight: bold;
padding: 5px;
border-radius: 5px;
border: solid #000 1px;
clear: both;
margin: bottom: 15px;
}
<header>
<h1>Simple Blackjack</h1>
</header>
<form>
<div>
<table>
<tr>
<td>Dealer Cards:</td>
<td><input id="dealer1" class="cards" type="text" name="dealer1" size="5" disabled="true" /> <input id="dealer2" class="cards" type="text" name="dealer2" size="5" disabled="true" /></td>
</tr>
<tr>
<td>Your Card Total:</td>
<td><input id="player" class="cards" type="text" name="player" size="5" disabled="true" /></td>
</tr>
</table>
</div>
<aside>
<input type="button" name="deal" value="Deal Card" onclick="dealCard()" class="button" /><br><br>
<input type="button" name="standButton" value="Stand" onclick="stand()" class="button" /><br><br>
<input type="button" name="newGame" value="New Game" onclick="dealer()" class="button" />
</aside>
</form>
Hidden Input type
Also, as #rayon suggested in a comment, the type attribute could be changed from text to hidden.
hidden: A control that is not displayed but whose value is submitted to the server.1
function dealer() {
//...set dealer1, dealer2
//set type to hidden to hide the element
document.getElementById("dealer2").type = "hidden";
}
function stand() {
//set type to text to display it as normal
document.getElementById("dealer2").type = "text";
var dealer1;
var dealer2;
var player;
function dealer() {
dealer1 = document.getElementById("dealer1").value = Math.random() * 11 + 1;
document.getElementById("dealer1").value = Math.floor(dealer1);
dealer2 = document.getElementById("dealer2").value = Math.random() * 11 + 1;
dealer2 = Math.floor(dealer2);
document.getElementById("dealer2").type = "hidden";
player = document.getElementById("player").value = Math.random() * 21 + 2;
document.getElementById("player").value = Math.floor(player);
}
function stand() {
document.getElementById("dealer2").type = "text";
}
function dealCard() {
}
body {
font-family: Arial;
}
section {
width: 600px;
height: 300px;
margin: auto;
background-color: #007929;
padding: 15px;
border-radius: 10px;
border: solid #000 2px;
}
header {
width: 550px;
height: 50px;
margin: auto;
margin-bottom: 15px;
text-align: center;
border-radius: 10px;
border: solid #000 1px;
}
h1 {
line-height: 10px;
}
div {
width: 400px;
height: 300px;
float: left;
}
aside {
width: 200px;
height: 300px;
float: right;
}
table {
width: 400px;
font-weight: bold;
color: #fff;
}
.cards {
background-color: #63dd8d;
border: solid #000 1px;
border-radius: 5px;
font-size: 14pt;
padding: 5px;
}
.button {
background-color: #009900;
width: 150px;
color: #fff;
font-weight: bold;
padding: 5px;
border-radius: 5px;
border: solid #000 1px;
clear: both;
margin: bottom: 15px;
}
<header>
<h1>Simple Blackjack</h1>
</header>
<form>
<div>
<table>
<tr>
<td>Dealer Cards:</td>
<td><input id="dealer1" class="cards" type="text" name="dealer1" size="5" disabled="true" /> <input id="dealer2" class="cards" type="hidden" name="dealer2" size="5" disabled="true" /></td>
</tr>
<tr>
<td>Your Card Total:</td>
<td><input id="player" class="cards" type="text" name="player" size="5" disabled="true" /></td>
</tr>
</table>
</div>
<aside>
<input type="button" name="deal" value="Deal Card" onclick="dealCard()" class="button" /><br><br>
<input type="button" name="standButton" value="Stand" onclick="stand()" class="button" /><br><br>
<input type="button" name="newGame" value="New Game" onclick="dealer()" class="button" />
</aside>
</form>
style (including CSS)
Another approach is to update element'style. Multiple styles can be used - e.g. display can be to none using .style:
function dealer() {
//...set dealer1, dealer2
document.getElementById("dealer2").style.display = "none";
Then to show the element (when the button labeled stand is clicked), set that display style to a value other than none (e.g. a blank string, inline, etc).
function stand() {
document.getElementById("dealer2").style.display = "";
}
See this demonstrated in the snippet below:
var dealer1;
var dealer2;
var player;
function dealer() {
dealer1 = document.getElementById("dealer1").value = Math.random() * 11 + 1;
document.getElementById("dealer1").value = Math.floor(dealer1);
dealer2 = document.getElementById("dealer2").value = Math.random() * 11 + 1;
dealer2 = Math.floor(dealer2);
document.getElementById("dealer2").style.display = "none";
player = document.getElementById("player").value = Math.random() * 21 + 2;
document.getElementById("player").value = Math.floor(player);
}
function stand() {
document.getElementById("dealer2").style.display = "inline";
}
function dealCard() {
}
body {
font-family: Arial;
}
section {
width: 600px;
height: 300px;
margin: auto;
background-color: #007929;
padding: 15px;
border-radius: 10px;
border: solid #000 2px;
}
header {
width: 550px;
height: 50px;
margin: auto;
margin-bottom: 15px;
text-align: center;
border-radius: 10px;
border: solid #000 1px;
}
h1 {
line-height: 10px;
}
div {
width: 400px;
height: 300px;
float: left;
}
aside {
width: 200px;
height: 300px;
float: right;
}
table {
width: 400px;
font-weight: bold;
color: #fff;
}
.cards {
background-color: #63dd8d;
border: solid #000 1px;
border-radius: 5px;
font-size: 14pt;
padding: 5px;
}
.button {
background-color: #009900;
width: 150px;
color: #fff;
font-weight: bold;
padding: 5px;
border-radius: 5px;
border: solid #000 1px;
clear: both;
margin: bottom: 15px;
}
<header>
<h1>Simple Blackjack</h1>
</header>
<form>
<div>
<table>
<tr>
<td>Dealer Cards:</td>
<td><input id="dealer1" class="cards" type="text" name="dealer1" size="5" disabled="true" /> <input id="dealer2" class="cards" type="text" name="dealer2" size="5" disabled="true" /></td>
</tr>
<tr>
<td>Your Card Total:</td>
<td><input id="player" class="cards" type="text" name="player" size="5" disabled="true" /></td>
</tr>
</table>
</div>
<aside>
<input type="button" name="deal" value="Deal Card" onclick="dealCard()" class="button" /><br><br>
<input type="button" name="standButton" value="Stand" onclick="stand()" class="button" /><br><br>
<input type="button" name="newGame" value="New Game" onclick="dealer()" class="button" />
</aside>
</form>
Or the visibility could be set to hidden in order to hide the element, and then set to visible to show it.
function dealer() {
//...set dealer1, dealer2
document.getElementById("dealer2").style.visibility = "hidden";
}
function stand() {
document.getElementById("dealer2").style.visibility = "visible";
CSS classes could also be utilized combined with the above techniques. For example, the following css rule could be added:
#dealer2.hidden {
visibility: hidden;
}
Then use that class style rule by adding the class with classList.add() and classList.remove():
function dealer() {
//...set dealer1, dealer2
document.getElementById("dealer2").classList.add("hidden");
}
function stand() {
document.getElementById("dealer2").classList.remove("visible");
var dealer1;
var dealer2;
var player;
function dealer() {
dealer1 = document.getElementById("dealer1").value = Math.random() * 11 + 1;
document.getElementById("dealer1").value = Math.floor(dealer1);
dealer2 = document.getElementById("dealer2").value = Math.random() * 11 + 1;
dealer2 = Math.floor(dealer2);
document.getElementById("dealer2").classList.add("hidden");
player = document.getElementById("player").value = Math.random() * 21 + 2;
document.getElementById("player").value = Math.floor(player);
}
function stand() {
document.getElementById("dealer2").classList.remove("hidden");;
}
function dealCard() {
}
body {
font-family: Arial;
}
section {
width: 600px;
height: 300px;
margin: auto;
background-color: #007929;
padding: 15px;
border-radius: 10px;
border: solid #000 2px;
}
header {
width: 550px;
height: 50px;
margin: auto;
margin-bottom: 15px;
text-align: center;
border-radius: 10px;
border: solid #000 1px;
}
h1 {
line-height: 10px;
}
div {
width: 400px;
height: 300px;
float: left;
}
aside {
width: 200px;
height: 300px;
float: right;
}
table {
width: 400px;
font-weight: bold;
color: #fff;
}
.cards {
background-color: #63dd8d;
border: solid #000 1px;
border-radius: 5px;
font-size: 14pt;
padding: 5px;
}
.button {
background-color: #009900;
width: 150px;
color: #fff;
font-weight: bold;
padding: 5px;
border-radius: 5px;
border: solid #000 1px;
clear: both;
margin: bottom: 15px;
}
#dealer2.hidden {
visibility: hidden;
}
<header>
<h1>Simple Blackjack</h1>
</header>
<form>
<div>
<table>
<tr>
<td>Dealer Cards:</td>
<td><input id="dealer1" class="cards" type="text" name="dealer1" size="5" disabled="true" /> <input id="dealer2" class="cards" type="text" name="dealer2" size="5" disabled="true" /></td>
</tr>
<tr>
<td>Your Card Total:</td>
<td><input id="player" class="cards" type="text" name="player" size="5" disabled="true" /></td>
</tr>
</table>
</div>
<aside>
<input type="button" name="deal" value="Deal Card" onclick="dealCard()" class="button" /><br><br>
<input type="button" name="standButton" value="Stand" onclick="stand()" class="button" /><br><br>
<input type="button" name="newGame" value="New Game" onclick="dealer()" class="button" />
</aside>
</form>
There are other techniques that will also accomplish the same requirement. Some javascript libraries (like jQuery) have wrappers for the techniques described above (e.g. jQuery's .hide() and .show()).
1https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-type)
To hide something with javascript:
document.getElementById("hello").style.display = 'none';
To show it again with javascript:
document.getElementById("hello").style.display = 'block';
Or you could just use JQuery instead.
You should use another name for function stand()
because name duplicated in <input type="button" name="stand" value="Stand" onclick="stand()" class="button" />
just use another name
To use Native javascript to change disabled attribute use document.getElementById("dealer2").disabled = false;
var dealer1;
var dealer2;
var player;
function dealer() {
dealer1 = document.getElementById("dealer1").value = Math.random() * 11 + 1;
document.getElementById("dealer1").value = Math.floor(dealer1);
dealer2 = document.getElementById("dealer2").value = Math.random() * 11 + 1;
dealer2 = Math.floor(dealer2);
document.getElementById("dealer2").value = "Hidden";
player = document.getElementById("player").value = Math.random() * 21 + 2;
document.getElementById("player").value = Math.floor(player);
}
function stnd() {
document.getElementById("dealer2").disabled = false;
dealer2 = document.getElementById("dealer2").value = "Changed";
}
function dealCard() {
}
body {
font-family: Arial;
background: url("cards.jpg");
}
section {
width: 600px;
height: 300px;
margin: auto;
background-color: #007929;
padding: 15px;
border-radius: 10px;
border: solid #000 2px;
}
header {
width: 550px;
height: 50px;
margin: auto;
margin-bottom: 15px;
background: url("cards.jpg");
text-align: center;
border-radius: 10px;
border: solid #000 1px;
}
h1 {
line-height: 10px;
}
div {
width: 400px;
height: 300px;
float: left;
}
aside {
width: 200px;
height: 300px;
float: right;
}
table {
width: 400px;
font-weight: bold;
color: #fff;
}
.cards {
background-color: #63dd8d;
border: solid #000 1px;
border-radius: 5px;
font-size: 14pt;
padding: 5px;
}
.button {
background-color: #009900;
width: 150px;
color: #fff;
font-weight: bold;
padding: 5px;
border-radius: 5px;
border: solid #000 1px;
clear: both;
margin: bottom: 15px;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Blackjack</title>
<meta charset="utf-8">
</head>
<body>
<section>
<header>
<h1>Simple Blackjack</h1>
</header>
<form>
<div>
<table>
<tr>
<td>Dealer Cards:</td>
<td><input id="dealer1" class="cards" type="text" name="dealer1" size="5" disabled="true" /> <input id="dealer2" class="cards" type="text" name="dealer2" size="5" disabled="true" /></td>
</tr>
<tr>
<td>Your Card Total:</td>
<td><input id="player" class="cards" type="text" name="player" size="5" disabled="true" /></td>
</tr>
</table>
</div>
<aside>
<input type="button" name="deal" value="Deal Card" onclick="dealCard()" class="button" /><br><br>
<input type="button" name="stand" value="Stand" onclick="stnd()" class="button" /><br><br>
<input type="button" name="newGame" value="New Game" onclick="dealer()" class="button" />
</aside>
</form>
</section>
</body>
</html>
If you want to use jQuery you can do this:
$('input').click(function() {
if ($('input').val() === "show") {
$('#name').show('700');
$('input').val("hide");
} else{
$('#name').hide('700');
$('input').val("show");
};
});
#name is id of your element. :D
It can be fetched using jQuery as shown below:
<input type="button" name="dealer2" value="Dealer2" style="display: none !important;" />
<input type="button" name="stand" value="Stand" onclick="stand()" class="button" />
<script>
function stand() {
$("#dealer2").show();
}
</script>
I am implementing a simple registration form. I want to validate if the user has selected at least one checkbox. All the fields in my form are being validated without page reload except for this one input field. When I try to validate this field, the page reloads and all the values that the user previously entered are lost. I want to prevent this from happening.
function validate() {
var checkbox1 = document.getElementById('three').checked;
var checkbox2 = document.getElementById('four').checked;
var checkbox3 = document.getElementById('five').checked;
var checkbox4 = document.getElementById('six').checked;
if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == true) {
if (referenceToForm.elements["usrgrp[]"].selectedIndex == -1) {
alert("Please enter all the required values");
}
}
if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
if (referenceToForm.elements["usrgrp[]"].selectedIndex == -1) {
alert("Please enter all the required values");
}
}
if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
if (referenceToForm.elements["usrgrp[]"].selectedIndex != -1) {
alert("Please enter all the required values");
}
}
if (document.getElementById('values').value == -1) {
alert("Please enter all the required values checkbox");
}
}
#import url("https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css");
#labels{
position: relative;
width: 250px;
float: left;
}
h3{
margin: 0px 0px 20px 0px;
}
#fields{
position: relative;
width: 250px;
float: left;
}
.element{
margin-bottom: 23px;
border: 1px solid #dadada;
border-color: #06a3e9;
box-shadow: 0 0 1px lightblue;
}
.different{
margin-top: 4px;
margin-bottom: 22px;
}
.values{
margin-bottom: 23px;
}
.heading, .feedback{
margin-top: 43px;
}
.preference{
border-color: #06a3e9;
box-shadow: 0 0 1px lightblue;
}
.multiple{
border-color: #06a3e9;
box-shadow: 0 0 1px lightblue;
margin-top: 20px;
}
textarea{
margin-top: 20px;
border: 1px solid #06a3e9;
box-shadow: 0 0 1px lightblue;
}
a{
color: #06a3e9;
}
.final{
margin-top: 15px;
}
.feedback{
margin-top: 73px;
}
#submit, #reset{
border: 1px solid #dadada;
border-color: #06a3e9;
box-shadow: 0 0 1px lightblue;
border-radius:5px;
}
input[type="checkbox"]{
display: none;
}
label:before{
width: 1em;
display: inline-block;
}
label{
margin-right: 5px;
}
input[type="checkbox"] + label:before{
font-family: FontAwesome;
display: inline-block;
content: "\f096";
letter-spacing: 5px;
color: #06a3e9;
display: inline-block;
}
input[type="checkbox"]:checked + label:before{
content:"\f14a";
display: inline-block;
color: #06a3e9;
}
input[type="radio"]{
display: none;
}
input[type="radio"] + label:before{
font-family: FontAwesome;
display: inline-block;
content:"\f10c";
font-size: 14px;
color: #06a3e9;
letter-spacing: 5px;
display: inline-block;
}
input[type="radio"]:checked + label:before{
content:"\f192";
font-size: 14px;
display: inline-block;
}
<!doctype html>
<html>
<head>
<title> Register here </title>
<link rel="stylesheet" href="../css/registration.css"/>
<script src = "../javascript/registration.js"></script>
</head>
<body>
<h1>Event Registration Form</h1>
<div id="labels">
<h3>Username</h3>
<h3>Password</h3>
<h3>Age</h3>
<h3>Email</h3>
<h3>Existing customer?</h3>
<h3>Select your preferences</h3>
<h3>Newsletter Preferences</h3>
<h3 class="heading">Menu Options</h3>
<h3 class="feedback">Send us your feedback !</h3>
</div>
<div id="fields">
<form action="#" method="get" name="referenceToForm">
<input type="text" name="Username" id="Username" class="element"required/>
<input type="password" name="Password" class="element" required/>
<input type="number" name="Age" class="element" required/>
<input type="email" name="Email" class="element" required/>
<div class="different">
<input type="radio" name="customer" id="one" checked="checked" />
<label for="one">Yes</label>
<input type="radio" name="customer" id="two" />
<label for="two">No</label>
</div>
<div class="values">
<input type="checkbox" name="interest" id="three" />
<label for="three">Dog</label>
<input type="checkbox" name="interest" id="four" />
<label for="four">Cat</label>
<input type="checkbox" name="interest" id="five" />
<label for="five">Parrot</label>
<input type="checkbox" name="interest" id="six" />
<label for="six">Possum</label>
<span id="spanning"> </span>
</div>
<select class="preference" id="preference" value="-1">
<option value="Entertainment">Entertainment</option>
<option value="Technology">Technology</option>
<option value="TV">TV</option>
</select>
<div class="menu">
<select multiple required id="multiple" class="multiple" value="-1" name="usrgrp[]">
<option value="Sports">Sports</option>
<option value="Politics">Politics</option>
<option value="News">News</option>
<option value="Swimming">Swimming</option>
<option value="Health">Health</option>
</select>
</div>
<textarea rows="5" cols="20" required></textarea>
<div class="final">
<input type="submit" name="submit" id="submit" onclick="validate()" />
<input type="reset" name="reset" id="reset" />
</div>
</form>
</div>
</body>
</html>
UPDATE
Thanks to everyone who tried to help me with this. Below is the code which solves my problem perfectly.
function validate() {
var checkbox1 = document.getElementById('three').checked;
var checkbox2 = document.getElementById('four').checked;
var checkbox3 = document.getElementById('five').checked;
var checkbox4 = document.getElementById('six').checked;
if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
alert("Please enter all the required values");
return false;
}
}
#import url("https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css");
#labels{
position: relative;
width: 250px;
float: left;
}
h3{
margin: 0px 0px 20px 0px;
}
#fields{
position: relative;
width: 250px;
float: left;
}
.element{
margin-bottom: 23px;
border: 1px solid #dadada;
border-color: #06a3e9;
box-shadow: 0 0 1px lightblue;
}
.different{
margin-top: 4px;
margin-bottom: 22px;
}
.values{
margin-bottom: 23px;
}
.heading, .feedback{
margin-top: 43px;
}
.preference{
border-color: #06a3e9;
box-shadow: 0 0 1px lightblue;
}
.multiple{
border-color: #06a3e9;
box-shadow: 0 0 1px lightblue;
margin-top: 20px;
}
textarea{
margin-top: 20px;
border: 1px solid #06a3e9;
box-shadow: 0 0 1px lightblue;
}
a{
color: #06a3e9;
}
.final{
margin-top: 15px;
}
.feedback{
margin-top: 73px;
}
#submit, #reset{
border: 1px solid #dadada;
border-color: #06a3e9;
box-shadow: 0 0 1px lightblue;
border-radius:5px;
}
input[type="checkbox"]{
display: none;
}
label:before{
width: 1em;
display: inline-block;
}
label{
margin-right: 5px;
}
input[type="checkbox"] + label:before{
font-family: FontAwesome;
display: inline-block;
content: "\f096";
letter-spacing: 5px;
color: #06a3e9;
display: inline-block;
}
input[type="checkbox"]:checked + label:before{
content:"\f14a";
display: inline-block;
color: #06a3e9;
}
input[type="radio"]{
display: none;
}
input[type="radio"] + label:before{
font-family: FontAwesome;
display: inline-block;
content:"\f10c";
font-size: 14px;
color: #06a3e9;
letter-spacing: 5px;
display: inline-block;
}
input[type="radio"]:checked + label:before{
content:"\f192";
font-size: 14px;
display: inline-block;
}
<!doctype html>
<html>
<head>
<title> Register here </title>
<link rel="stylesheet" href="../css/registration.css"/>
<script src = "../javascript/registration.js"></script>
</head>
<body>
<h1>Event Registration Form</h1>
<div id="labels">
<h3>Username</h3>
<h3>Password</h3>
<h3>Age</h3>
<h3>Email</h3>
<h3>Existing customer?</h3>
<h3>Select your preferences</h3>
<h3>Newsletter Preferences</h3>
<h3 class="heading">Menu Options</h3>
<h3 class="feedback">Send us your feedback !</h3>
</div>
<div id="fields">
<form action="#" method="get" name="referenceToForm">
<input type="text" name="Username" id="Username" class="element"required/>
<input type="password" name="Password" class="element" required/>
<input type="number" name="Age" class="element" required/>
<input type="email" name="Email" class="element" required/>
<div class="different">
<input type="radio" name="customer" id="one" checked="checked" />
<label for="one">Yes</label>
<input type="radio" name="customer" id="two" />
<label for="two">No</label>
</div>
<div class="values">
<input type="checkbox" name="interest" id="three" />
<label for="three">Dog</label>
<input type="checkbox" name="interest" id="four" />
<label for="four">Cat</label>
<input type="checkbox" name="interest" id="five" />
<label for="five">Parrot</label>
<input type="checkbox" name="interest" id="six" />
<label for="six">Possum</label>
<span id="spanning"> </span>
</div>
<select class="preference" id="preference" value="-1">
<option value="Entertainment">Entertainment</option>
<option value="Technology">Technology</option>
<option value="TV">TV</option>
</select>
<div class="menu">
<select multiple required id="multiple" class="multiple" value="-1" name="usrgrp[]">
<option value="Sports">Sports</option>
<option value="Politics">Politics</option>
<option value="News">News</option>
<option value="Swimming">Swimming</option>
<option value="Health">Health</option>
</select>
</div>
<textarea rows="5" cols="20" required></textarea>
<div class="final">
<input type="submit" name="submit" id="submit" onclick="return validate()" />
<input type="reset" name="reset" id="reset" />
</div>
</form>
</div>
</body>
</html>
I've spotted 2 problems with your form and both are easy to fix.
Your validation function must return either true to submit the form or false to cancel. If you don't supply a return value, as in your code, the form will always be submitted:
<input type="submit" name="submit" id="submit" onclick="validate()" >
To fix this you need to have your validation function return a value which is returned to the onclick handler:
<input type="submit" name="submit" id="submit" onclick="return validate()" >
This line in the validation function throws an error because there are no elements with id="values". You will need to remove or fix this code so that your function completes normally and returns either a true or false value.
if (document.getElementById('values').value == -1) {
alert("Please enter all the required values checkbox");
}
Perhaps someone can comment on this, but I've always seen validation handled in the form onsubmit event rather than the submit button onclick event. Yet, perhaps this is just convention as it appears to work either way:
<form onsubmit="return validate()" ...
<input type="submit" onclick="return validate()" ...
The main thing, if you are using jsFiddle, is to use this method of initializing functions:
window.validate = function() {
and not like this:
function validate() {
Here is my stab at it. No Angular, nor JQuery used, although I recommend learning each of them. I messed up your submit button, but its easily fixed with css. I also added a fake submit button which triggers the verification only. If it passes verification, then it can continue to send. My jsfiddle:
http://jsfiddle.net/omikey/tfk7d3ks/
<div class="container">
<div id="labels">
<h3>Username </h3>
<h3>Password</h3>
<h3>Age</h3>
<h3>Email</h3>
<h3>Existing customer?</h3>
<h3>Select your preferences</h3>
<h3>Newsletter Preferences</h3>
<h3 class="heading">Menu Options</h3>
<h3 class="feedback">Send us your feedback !</h3>
</div>
<div id="fields">
<form action="#" method="get" name="referenceToForm">
<div>
<input type="text" name="Username" id="Username" class="element" required/>
</div>
<div>
<input type="password" name="Password" class="element" required/>
</div>
<div>
<input type="number" name="Age" class="element" required/>
</div>
<div>
<input type="email" name="Email" class="element" required/>
</div>
<div class="different">
<input type="radio" name="customer" id="one" checked="checked" />
<label for="one">Yes</label>
<input type="radio" name="customer" id="two" />
<label for="two">No</label>
</div>
<div class="value">
<input type="checkbox" name="interest" id="three" />
<label for="three">Dog</label>
<input type="checkbox" name="interest" id="four" />
<label for="four">Cat</label>
<input type="checkbox" name="interest" id="five" />
<label for="five">Parrot</label>
<input type="checkbox" name="interest" id="six" />
<label for="six">Possum</label>
<span id="spanning"> </span>
</div>
<div>
<select class="preference" id="preference" value="-1">
<option value="Entertainment">Entertainment</option>
<option value="Technology">Technology</option>
<option value="TV">TV</option>
</select>
</div>
<div class="menu">
<select multiple id="multiple" class="multiple" value="-1" name="usrgrp[]">
<option value="Sports">Sports</option>
<option value="Politics">Politics</option>
<option value="News">News</option>
<option value="Swimming">Swimming</option>
<option value="Health">Health</option>
</select>
<span id="spanElement"> </span>
</div>
<div class="comment">
<textarea rows="5" cols="20" required></textarea>
</div>
<div class="final">
<input type="button" name="verify" onclick="validate()" />
<input type="submit" name="submit" style="display:none" id="submit" />
<input type="reset" name="reset" id="reset" />
</div>
</form>
</div>
</div>
#import url("https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css");
.container{
width: 100%;
margin-left: 400px;
}
#spanning{
color: #06a3e9;
}
.nav ul{
width: 150px;
float: left;
background-color: #dadada;
padding: 0px;
margin: 0px;
}
.nav li{
list-style-type: none;
}
.nav a{
color:#000;
cursor:pointer;
display: block;
line-height: 40px;
text-indent: 10px;
text-decoration: none;
font-weight: bold;
}
.nav ul ul li{
display: none;
}
.nav li:hover ul li{
display: block;
}
.subnav ul{
position: relative;
background: #dadada;
}
#labels{
position: relative;
width: 250px;
top:80px;
float: left;
}
h3{
margin: 0px 0px 20px 0px;
}
#fields{
position: relative;
width: 250px;
top:80px;
float: left;
}
.element{
margin-bottom: 23px;
border: 1px solid #dadada;
border-color: #06a3e9;
box-shadow: 0 0 1px lightblue;
}
.different{
margin-top: 4px;
margin-bottom: 22px;
}
.value{
margin-bottom: 23px;
}
.heading, .feedback{
margin-top: 43px;
}
.preference{
border-color: #06a3e9;
box-shadow: 0 0 1px lightblue;
}
.multiple{
border-color: #06a3e9;
box-shadow: 0 0 1px lightblue;
margin-top: 20px;
}
textarea{
margin-top: 20px;
border: 1px solid #06a3e9;
box-shadow: 0 0 1px lightblue;
}
a{
color: #06a3e9;
}
.final{
margin-top: 15px;
}
.feedback{
margin-top: 73px;
}
#submit, #reset{
border: 1px solid #dadada;
border-color: #06a3e9;
box-shadow: 0 0 1px lightblue;
border-radius:5px;
}
input[type="checkbox"]{
display: none;
}
label:before{
width: 1em;
display: inline-block;
}
label{
margin-right: 5px;
}
input[type="checkbox"] + label:before{
font-family: FontAwesome;
display: inline-block;
content: "\f096";
letter-spacing: 5px;
color: #06a3e9;
display: inline-block;
}
input[type="checkbox"]:checked + label:before{
content:"\f14a";
display: inline-block;
color: #06a3e9;
}
input[type="radio"]{
display: none;
}
input[type="radio"] + label:before{
font-family: FontAwesome;
display: inline-block;
content:"\f10c";
font-size: 14px;
color: #06a3e9;
letter-spacing: 5px;
display: inline-block;
}
input[type="radio"]:checked + label:before{
content:"\f192";
font-size: 14px;
display: inline-block;
}
window.validate = function() {
var valid = true;
var checkbox1 = document.getElementById('three').checked;
var checkbox2 = document.getElementById('four').checked;
var checkbox3 = document.getElementById('five').checked;
var checkbox4 = document.getElementById('six').checked;
if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == true) {
if (referenceToForm.elements["usrgrp[]"].selectedIndex == -1) {
alert("Please enter all the required values");
valid = false;
}
}
if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
if (referenceToForm.elements["usrgrp[]"].selectedIndex == -1) {
alert("Please enter all the required values");
valid = false;
}
}
if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
if (referenceToForm.elements["usrgrp[]"].selectedIndex != -1) {
alert("Please enter all the required values");
valid = false;
}
}
if (document.getElementById('multiple').value == -1)
{
alert("Please enter all the required values");
valid = false;
}
if (document.getElementById('preference').value == -1)
{
alert("Please enter all the required values");
valid = false;
}
if (valid)
{
document.getElementById('submit').click();
}
}