How to swap text both on hover and onclick - javascript

I have a default message on the top of a donation form and I would like it to change dynamically depending on which amount the user hovers or clicks.
Each amount as well as "€Other" should have a corresponding message. For Example: "with €5.00 we can accomplish this..." With €10.00 we could do that..."
These messages should change accordingly on hover but also remain visible if the corresponding option is selected.
If the user deselects a previously selected option or if no option is selected, the default message should reappear.
I've tried different methods without success, I would really appreciate some help making this happen.
FIDDLE
HTML
<p>Choose below the amount of your donation</p>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">
<input type="hidden" name="cmd" value="_donations">
<input type="hidden" name="business" value="louzanimalespaypal#gmail.com">
<label><input type="checkbox" name="amount" class="checkbutton" value="5,00"><span>€05.00</span></label>
<label><input type="checkbox" name="amount" class="checkbutton" value="10,00"><span>€10.00</span></label>
<label><input type="checkbox" name="amount" class="checkbutton" value="15,00"><span>€15.00</span></label>
<label><input type="checkbox" name="amount" class="checkbutton" value="20,00"><span>€20.00</span></label>
<input type="number" class="textBox" name="amount" placeholder="€ Other">
<input type="hidden" name="item_name" value="Donation">
<input type="hidden" name="item_number" value="Donation">
<input type="hidden" name="currency_code" value="EUR">
<input type="hidden" name="lc" value="PT">
<input type="hidden" name="bn" value="Louzanimales_Donation_WPS_PT">
<input type="hidden" name="return" value="http://www.louzanimales.py/agradecimentos.htm">
<br style="clear: both;"/>
<input class="donation-button" type="submit" value="Send Donation">
</form>
JavaScript
$('input.checkbutton').on('change', function() {
$('input.checkbutton').not(this).prop('checked', false);
});
$(".textBox").focus(function() {
$(".checkbutton").prop("checked", false);
});
$(".checkbutton").change(function() {
if($(this).is(":checked")) {
$(".textBox").val("");
}
});
CSS
body {
box-sizing: border-box;
padding: 50px;
font-family: sans-serif;
font-size: 18px;
text-align: center;
}
label {
margin: 1%;
float: left;
background: #ccc;
text-align: center;
width: 18%;
}
label:hover {
background: grey;
color: #fff;
}
label span {
text-align: center;
box-sizing: border-box;
padding: 10px 0;
display: block;
}
label input {
display: none;
left: 0;
top: -10px;
}
input:checked + span {
background-color: black;
color: #fff;
}
/* Hide HTML5 Up and Down arrows in input type="number" */
input[type=number] {-moz-appearance: textfield;}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
appearance: none;
margin: 0;
}
.textBox {
margin: 1%;
float: left;
background: #ccc;
border: 0;
padding: 10px 0;
text-align: center;
font-family: sans-serif;
font-size: 18px;
width: 18%;
-webkit-box-sizing: border-box; /* For legacy WebKit based browsers */
-moz-box-sizing: border-box; /* For all Gecko based browsers */
box-sizing: border-box;
}
.textBox:focus {
box-shadow:none;
box-shadow:inset 0 0 4px 0 #000;
-moz-box-shadow:inset 0 0 4px 0 #000;
-wevkit-box-shadow:inset 0 0 4px 0 #000;
}
.donation-button {
width: 98%;
margin: 1%;
border: 0;
background: grey;
color: white;
text-align: center;
font-family: sans-serif;
font-size: 18px;
padding: 10px 0 10px 0;
-webkit-box-sizing: border-box; /* For legacy WebKit based browsers */
-moz-box-sizing: border-box; /* For all Gecko based browsers */
box-sizing: border-box;
}
.donation-button:hover {
background: black;
}

David! Finally i improved it :)
You can customize your own message in HTML seperatly by data-alertOnHover which shown on hover on button or textBox and data-alertAfter which shown select a button or type a number in textBox. It covers all of states as well as less cumbersome.
Also
if the user deselects a previously selected option or if no option is
selected, the default message will reappear.
var defaultTxt = $('#alert').text();
var checked;
$('input.checkbutton').change(function() {
if ($(this).is(":checked")) {
$(".textBox").val("");
$('#alert').text($(this).attr("data-alertAfter") + $(this).val());
checked = $(this);
}
else
{
$('#alert').text(defaultTxt);
checked = undefined;
}
$('input.checkbutton').not(this).prop('checked', false);
});
$('.input-container').hover(
function() {
$('#alert').text($(this).children('input').attr("data-alertOnHover"));
},
function() {
if (checked)
$('#alert').text($(checked).attr("data-alertAfter") + $(checked).val());
else
$('#alert').text(defaultTxt);
}
);
$(".textBox").focus(function() {
checked = undefined;
$(".checkbutton").prop("checked", false)
}).blur(function() {
if ($(this).val() != "") {
checked = $(this);
$('#alert').text($(this).attr("data-alertAfter") + $(this).val())
}
});
body {
box-sizing: border-box;
padding: 50px;
font-family: sans-serif;
font-size: 18px;
text-align: center;
}
label {
margin: 1%;
float: left;
background: #ccc;
text-align: center;
width: 18%;
}
label:hover {
background: grey;
color: #fff;
}
label span {
text-align: center;
box-sizing: border-box;
padding: 10px 0;
display: block;
}
label input {
display: none;
left: 0;
top: -10px;
}
input:checked + span {
background-color: black;
color: #fff;
}
/* Hide HTML5 Up and Down arrows in input type="number" */
input[type=number] {
-moz-appearance: textfield;
}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
appearance: none;
margin: 0;
}
.textBox {
margin: 1%;
float: left;
background: #ccc;
border: 0;
padding: 10px 0;
text-align: center;
font-family: sans-serif;
font-size: 18px;
width: 18%;
-webkit-box-sizing: border-box;
/* For legacy WebKit based browsers */
-moz-box-sizing: border-box;
/* For all Gecko based browsers */
box-sizing: border-box;
}
.textBox:focus {
box-shadow: none;
box-shadow: inset 0 0 4px 0 #000;
-moz-box-shadow: inset 0 0 4px 0 #000;
-wevkit-box-shadow: inset 0 0 4px 0 #000;
}
.donation-button {
width: 98%;
margin: 1%;
border: 0;
background: grey;
color: white;
text-align: center;
font-family: sans-serif;
font-size: 18px;
padding: 10px 0 10px 0;
-webkit-box-sizing: border-box;
/* For legacy WebKit based browsers */
-moz-box-sizing: border-box;
/* For all Gecko based browsers */
box-sizing: border-box;
}
.donation-button:hover {
background: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p id="alert">Choose below the amount of your donation</p>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">
<input type="hidden" name="cmd" value="_donations">
<input type="hidden" name="business" value="louzanimalespaypal#gmail.com">
<label class="input-container">
<input type="checkbox" name="amount" class="checkbutton" value="5,00" data-alertOnHover="With €5.00 we can accomplish this..." data-alertAfter="Your donation will be €"><span>€05.00</span></label>
<label class="input-container">
<input type="checkbox" name="amount" class="checkbutton" value="10,00" data-alertOnHover="With €10.00 we could do that..." data-alertAfter="Your donation will be €"><span>€10.00</span></label>
<label class="input-container">
<input type="checkbox" name="amount" class="checkbutton" value="15,00" data-alertOnHover="With €15.00 we could do that..." data-alertAfter="Your donation will be €"><span>€15.00</span></label>
<label class="input-container">
<input type="checkbox" name="amount" class="checkbutton" value="20,00" data-alertOnHover="With €20,00 we could do more than that..." data-alertAfter="Your donation will be €"><span>€20.00</span></label>
<span class="input-container">
<input type="number" class="textBox" name="amount" placeholder="€ Other" data-alertOnHover="just type how much you want to donate..." data-alertAfter="Your donation will be €">
</span>
<input type="hidden" name="item_name" value="Donation">
<input type="hidden" name="item_number" value="Donation">
<input type="hidden" name="currency_code" value="EUR">
<input type="hidden" name="lc" value="PT">
<input type="hidden" name="bn" value="Louzanimales_Donation_WPS_PT">
<input type="hidden" name="return" value="http://www.louzanimales.py/agradecimentos.htm">
<br style="clear: both;" />
<input class="donation-button" type="submit" value="Send Donation">
</form>

i think this is exactly do what you need.
JSFIDDLE
HTML is not changed but "id" of:
<p id="alert">Choose below the amount of your donation</p>
Javascript
var defaultTxt = $('#alert').text();
$('input.checkbutton').change( function() {
$('input.checkbutton').not(this).prop('checked', false);
if($(this).is(":checked")) {
$(".textBox").val("");
}
var check = $(this).prop('checked');
var value = $(this).val();
switch(value)
{
case("5,00"):
if(check)
$('#alert').text("with €5.00 we can accomplish this...");
else
$('#alert').text(defaultTxt);
break;
case("10,00"):
if(check)
$('#alert').text("With €10.00 we could do that...");
else
$('#alert').text(defaultTxt);
break;
case("15,00"):
if(check)
$('#alert').text("With €15.00 we could do that...");
else
$('#alert').text(defaultTxt);
break;
case("20,00"):
if(check)
$('#alert').text("With €20,00 we could do more than that...");
else
$('#alert').text(defaultTxt);
break;
default:
$('#alert').text("");
break;
}
});
$('input.checkbutton').hover(function() {
alert();
},function() {
}
);
$('input.checkbutton').parent().hover(
function() {
var value = $(this).children('input.checkbutton').val();
switch(value)
{
case("5,00"):
$('#alert').text("with €5.00 we can accomplish this...");
break;
case("10,00"):
$('#alert').text("With €10.00 we could do that...");
break;
case("15,00"):
$('#alert').text("With €15.00 we could do that...");
break;
case("20,00"):
$('#alert').text("With €20,00 we could do more than that...");
break;
default:
$('#alert').text("");
break;
}
}, function() {
var othervalue = $('input.checkbutton:checked').val();
switch(othervalue)
{
case("5,00"):
$('#alert').text("with €5.00 we can accomplish this...");
break;
case("10,00"):
$('#alert').text("With €10.00 we could do that...");
break;
case("15,00"):
$('#alert').text("With €15.00 we could do that...");
break;
case("20,00"):
$('#alert').text("With €20,00 we could do more than that...");
break;
default:
$('#alert').text("");
break;
}
}
);
$(".textBox").focus(function() {
$(".checkbutton").prop("checked", false);
$('#alert').text(defaultTxt);
});
$(".textBox").blur(function() {
var txtVal = $(this).val();
if(txtVal != "")
$('#alert').text("With €"+ txtVal +" we could do that");
});

You can use data attributes for input fields, and data can hold text. Also, to achieve desired functionality, you could set 'flag' which will check if option is selected and 'lock' text (so it will not change on hover). Something like this:
locked=false;
$('input.checkbutton').on('change', function() {
$('#desc').text( $(this).data('text') );
if($(this).prop('checked')) {
locked=true;
}
else {
locked=false;
}
$('input.checkbutton').not(this).prop('checked', false);
});
$(".textBox").focus(function() {
$(".checkbutton").prop("checked", false);
});
$(".checkbutton").change(function() {
if($(this).is(":checked")) {
$(".textBox").val("");
}
});
default_text="Choose below the amount of your donation";
$( 'label').hover(
function() {
if(!locked)
$('#desc').text( $(this).children().data('text') );
}, function() {
if(!locked)
$('#desc').text( default_text );
}
);
body {
box-sizing: border-box;
padding: 50px;
font-family: sans-serif;
font-size: 18px;
text-align: center;
}
label {
margin: 1%;
float: left;
background: #ccc;
text-align: center;
width: 18%;
}
label:hover {
background: grey;
color: #fff;
}
label span {
text-align: center;
box-sizing: border-box;
padding: 10px 0;
display: block;
}
label input {
display: none;
left: 0;
top: -10px;
}
input:checked + span {
background-color: black;
color: #fff;
}
/* Hide HTML5 Up and Down arrows in input type="number" */
input[type=number] {-moz-appearance: textfield;}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
appearance: none;
margin: 0;
}
.textBox {
margin: 1%;
float: left;
background: #ccc;
border: 0;
padding: 10px 0;
text-align: center;
font-family: sans-serif;
font-size: 18px;
width: 18%;
-webkit-box-sizing: border-box; /* For legacy WebKit based browsers */
-moz-box-sizing: border-box; /* For all Gecko based browsers */
box-sizing: border-box;
}
.textBox:focus {
box-shadow:none;
box-shadow:inset 0 0 4px 0 #000;
-moz-box-shadow:inset 0 0 4px 0 #000;
-wevkit-box-shadow:inset 0 0 4px 0 #000;
}
.donation-button {
width: 98%;
margin: 1%;
border: 0;
background: grey;
color: white;
text-align: center;
font-family: sans-serif;
font-size: 18px;
padding: 10px 0 10px 0;
-webkit-box-sizing: border-box; /* For legacy WebKit based browsers */
-moz-box-sizing: border-box; /* For all Gecko based browsers */
box-sizing: border-box;
}
.donation-button:hover {
background: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="desc">Choose below the amount of your donation</p>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">
<input type="hidden" name="cmd" value="_donations">
<input type="hidden" name="business" value="louzanimalespaypal#gmail.com">
<label><input type="checkbox" name="amount" class="checkbutton" value="5,00" data-text="With 5 euros we can..."><span>€05.00</span></label>
<label><input type="checkbox" name="amount" class="checkbutton" value="10,00" data-text="With 10 euros we can..."><span>€10.00</span></label>
<label><input type="checkbox" name="amount" class="checkbutton" value="15,00" data-text="With 15 euros we can..."><span>€15.00</span></label>
<label><input type="checkbox" name="amount" class="checkbutton" value="20,00" data-text="With 20 euros we can..."><span>€20.00</span></label>
<input type="number" class="textBox" name="amount" placeholder="€ Other">
<input type="hidden" name="item_name" value="Donation">
<input type="hidden" name="item_number" value="Donation">
<input type="hidden" name="currency_code" value="EUR">
<input type="hidden" name="lc" value="PT">
<input type="hidden" name="bn" value="Louzanimales_Donation_WPS_PT">
<input type="hidden" name="return" value="http://www.louzanimales.py/agradecimentos.htm">
<br style="clear: both;"/>
<input class="donation-button" type="submit" value="Send Donation">
</form>
P.S. If i didn't understand your requirements, and you want text changing on hover, even when option is selected, you can just remove locked var...
EDIT: I think it is perfect now: https://jsfiddle.net/y05uzdzc/ based on your description.

When I run into stuff like this, I pick or create a way to easily distinguish one input from the others.
Unique ID's make it quick, and easy to find. In this example, your 5 Euro donation would get the ID of donation-5.
$("body").on("mouseover", "input", function () {
if ($(this).attr("id") === "donation-5") {
// --> DO your hover thing.
} else if (so forth and so on...){
// .....
}
})
Also, I'd consider using HTML5 button tags.
Ah yes... Nearly forgot, you want to monitor two event types
You'll need two 'event listeners':
The one I listed above, as well as the one that follows:
$("body").on("click", "input", function () {
if ($(this).attr("id") === "donation-5") {
// --> DO your hover thing.
} else if (so forth and so on...){
// .....
}
})

First, I think you want radio buttons instead of checkboxes. Once you make that change, I would just capture the change and hover events.
On change, you can always update your message. On hover, see if any of the items are checked, if so, leave the message, otherwise you can change it.
Here's a running example:
$(".donation").hover(function() {
let checkCount = $("form .donation :checked").length;
if (checkCount == 0) {
setMessage(this);
}
}).change(function() {
setMessage(this);
});
function setMessage(item) {
var text = $(item).text();
$("#message").text("Thanks for pledge of " + text);
}
body {
box-sizing: border-box;
padding: 50px;
font-family: sans-serif;
font-size: 18px;
text-align: center;
}
label {
margin: 1%;
float: left;
background: #ccc;
text-align: center;
width: 18%;
}
label:hover {
background: grey;
color: #fff;
}
label span {
text-align: center;
box-sizing: border-box;
padding: 10px 0;
display: block;
}
label input {
display: none;
left: 0;
top: -10px;
}
input:checked + span {
background-color: black;
color: #fff;
}
/* Hide HTML5 Up and Down arrows in input type="number" */
input[type=number] {
-moz-appearance: textfield;
}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
appearance: none;
margin: 0;
}
.textBox {
margin: 1%;
float: left;
background: #ccc;
border: 0;
padding: 10px 0;
text-align: center;
font-family: sans-serif;
font-size: 18px;
width: 18%;
-webkit-box-sizing: border-box;
/* For legacy WebKit based browsers */
-moz-box-sizing: border-box;
/* For all Gecko based browsers */
box-sizing: border-box;
}
.textBox:focus {
box-shadow: none;
box-shadow: inset 0 0 4px 0 #000;
-moz-box-shadow: inset 0 0 4px 0 #000;
-wevkit-box-shadow: inset 0 0 4px 0 #000;
}
.donation-button {
width: 98%;
margin: 1%;
border: 0;
background: grey;
color: white;
text-align: center;
font-family: sans-serif;
font-size: 18px;
padding: 10px 0 10px 0;
-webkit-box-sizing: border-box;
/* For legacy WebKit based browsers */
-moz-box-sizing: border-box;
/* For all Gecko based browsers */
box-sizing: border-box;
}
.donation-button:hover {
background: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="message">Choose below the amount of your donation</p>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">
<input type="hidden" name="cmd" value="_donations">
<input type="hidden" name="business" value="louzanimalespaypal#gmail.com">
<label class="donation">
<input type="radio" name="amount" class="checkbutton" value="5,00"><span>€05.00</span>
</label>
<label class="donation">
<input type="radio" name="amount" class="checkbutton" value="10,00"><span>€10.00</span>
</label>
<label class="donation">
<input type="radio" name="amount" class="checkbutton" value="15,00"><span>€15.00</span>
</label>
<label class="donation">
<input type="radio" name="amount" class="checkbutton" value="20,00"><span>€20.00</span>
</label>
<input type="number" class="textBox" name="amount" placeholder="€ Other">
<input type="hidden" name="item_name" value="Donation">
<input type="hidden" name="item_number" value="Donation">
<input type="hidden" name="currency_code" value="EUR">
<input type="hidden" name="lc" value="PT">
<input type="hidden" name="bn" value="Louzanimales_Donation_WPS_PT">
<input type="hidden" name="return" value="http://www.louzanimales.py/agradecimentos.htm">
<br style="clear: both;" />
<input class="donation-button" type="submit" value="Send Donation">
</form>

First of all, do not trust that clicking is the only of way of selecting a checkbox. An user can very well tab his way to it and spacebar its change.
Secondly, the behavior you want is radio button, not checkboxes.
This is how I'd do it:
HTML
<p id="myTextIdentifier">Choose below the amount of your donation</p>
... <!- Hidden for brevity ->
<label><input type="radio" name="amount" data-message="Value is 5 message" value="5,00"><span>€05.00</span></label>
<label><input type="radio" name="amount" data-message="Value is 10 message" value="10,00"><span>€10.00</span></label>
<label><input type="radio" name="amount" data-message="Value is 15 message" value="15,00"><span>€15.00</span></label>
<label><input type="radio" name="amount" data-message="Value is 20 message" value="20,00"><span>€20.00</span></label>
<input type="number" name="amount" data-message="Other value message" placeholder="€ Other">
JavaScript
$('#otherValueIdentifier')
.focus(function() {
$(':radio').prop('checked', false);
})
.change(function() {
changeText($(this).val().length
? $(this).data('message')
: '');
});
$(':radio').change(function() {
changeText($(this).is(':checked')
? $(this).data('message')
: '');
});
// Please keep in mind that this has a few flaws, I'll revise it later
$('[data-message]').hover(function () {
// this is the mouseEnter function
changeText($(this).data('message'));
}, function() {
// this is the mouseLeave function
changeText($('[data-message]:checked').data('message'));
});
function changeText(text) {
$('#myTextIdentifier').val(text || 'Default message');
}

Related

my html form on submitting is not calling the function password validation is there anything wrong with the code?

<html>
<script>
function passwordvalidation() #validate if password is strong and if botth passwords are equal
{
var x=document.forms["signup"]["psw"].value;
var y=document.form["signup"]["psw-repeat"].value;
var z=document.form["signup"]["email"].value;
alert(x);
if (x == ""||y==""||z=="") {
alert("form must be filled out");
return false;
}
else if(y!=x)
{
alert("password does not match");
return false;
}
else if (!(x.match(/[a-z]/g) && x.match(
/[A-Z]/g) && x.match(
/[0-9]/g) && x.match(
/[^a-zA-Z\d]/g) && x.length >= 8))
{
alert("weak password")
return false;
}
else
{
return true;
}
}
</script>
<style>
body {font-family: Arial, Helvetica, sans-serif;}
* {box-sizing: border-box}
/* Full-width input fields */
input[type=text], input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #f1f1f1;
}
input[type=text]:focus, input[type=password]:focus {
background-color: #ddd;
outline: none;
}
hr {
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}
/* Set a style for all buttons */
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
}
button:hover {
opacity:1;
}
/* Extra styles for the cancel button */
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}
/* Float cancel and signup buttons and add an equal width */
.cancelbtn, .signupbtn {
float: left;
width: 50%;
}
/* Add padding to container elements */
.container {
padding: 16px;
}
/* Clear floats */
.clearfix::after {
content: "";
clear: both;
display: table;
}
/* Change styles for cancel button and signup button on extra small screens */
#media screen and (max-width: 300px) {
.cancelbtn, .signupbtn {
width: 100%;
}
}
</style>
<body>
<form name="signup" action="/login" onsubmit="return passwordvalidation()" style="border:1px solid #ccc">
<div class="container">
<h1>Sign Up</h1>
<h6>Please fill in this form to create an account.</h6>
<p>Strong password must contain 8 characters </p>
<hr>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<div class="clearfix">
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</body>
</html>
You have several errors in these lines:
var x=document.forms["signup"]["psw"].value;
var y=document.form["signup"]["psw-repeat"].value;
var z=document.form["signup"]["email"].value;
You can use many methods to retrieve the inputs values, but this way is throwing errors. Check how to do it by using document.getElementBy*** or similar
It is calling the validation function, but you made a spelling mistake in second and third line. Correct
document.form --> document.forms document.form is undefined and your function is exiting with TypeError when you call document.form["signup"] without returning false, and thus your form is navigating to defined action
function passwordvalidation(form)
{
var x=form["psw"].value;
var y=form["psw-repeat"].value;
var z=form["email"].value;
if (x == ""||y==""||z=="") {
alert("form must be filled out");
console.log("form must be filled out");
return false;
}
else if(y!=x)
{
alert("password does not match");
return false;
}
else if (!(x.match(/[a-z]/g) && x.match(
/[A-Z]/g) && x.match(
/[0-9]/g) && x.match(
/[^a-zA-Z\d]/g) && x.length >= 8))
{
alert("weak password")
return false;
}
else
{
return true;
}
}
body {font-family: Arial, Helvetica, sans-serif;}
* {box-sizing: border-box}
/* Full-width input fields */
input[type=text], input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #f1f1f1;
}
input[type=text]:focus, input[type=password]:focus {
background-color: #ddd;
outline: none;
}
hr {
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}
/* Set a style for all buttons */
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
}
button:hover {
opacity:1;
}
/* Extra styles for the cancel button */
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}
/* Float cancel and signup buttons and add an equal width */
.cancelbtn, .signupbtn {
float: left;
width: 50%;
}
/* Add padding to container elements */
.container {
padding: 16px;
}
/* Clear floats */
.clearfix::after {
content: "";
clear: both;
display: table;
}
/* Change styles for cancel button and signup button on extra small screens */
#media screen and (max-width: 300px) {
.cancelbtn, .signupbtn {
width: 100%;
}
}
<form name="signup" action="/login" onsubmit="return passwordvalidation(this)" style="border:1px solid #ccc">
<div class="container">
<h1>Sign Up</h1>
<h6>Please fill in this form to create an account.</h6>
<p>Strong password must contain 8 characters </p>
<hr>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<div class="clearfix">
<button type="submit"class="signupbtn">Sign Up</button>
</div>
</div>
</form>

How to calculate percentage with simple JavaScript code

I have already created a form in html and linked it with my style sheet and also JavaScript page.
My problem is displaying the result on the form.
Can someone please take a look at the JavaScript code and tell me what I am doing wrong?
See the snippet for more details
// Percentage Calculator
const myForm = document.getElementById('my-form');
myForm.onsubmit = e=>e.preventDefault() // disable form submit
;
myForm.oninput = percentageCalculator;
function percentageCalculator(amount, percent) {
return ((percent *amount) / 100).toFixed(2)
}
myForm.result.value = percentageCalculator()
fieldset { margin-top: 1em;
}
label {
display: inline-block; width: 8em; text-align: left;
}
input {
font-size: .8em; text-align: left; display: inline-block; width: 8em;
}
output::before {
content: '';
}
output {
font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
}
<h2>Percentage Calculator</h2>
<form action="" id="my-form">
<fieldset>
<legend>Calculate Percentage :</legend>
<append>What is <input type="number" name="percent" step=any min=0> % of </append>
<label><input type="number" class="amount" step=any min=0></label>
</fieldset>
<fieldset><br>
<legend>Result :</legend>
<output name="result" value='0'></output>
<br><br>
<button type="reset">Reset Calculator!</button>
</fieldset>
</form>
If you want to make result instantly on click of the input boxes then, make addEventListerner to input elements then get the value inside percentageCalculator and make calculation accordingly..
I have not modified anything from your HTML and only modified the JS part..
const myForm = document.getElementById('my-form');
const percent = document.querySelector('[name="percent"]');
const amount = document.querySelector('.amount');
const result = document.querySelector('[name="result"]');
function percentageCalculator() {
result.value = ((percent.value * amount.value) / 100).toFixed(2)
}
myForm.addEventListener('submit', e=>e.preventDefault())
myForm.addEventListener('input', percentageCalculator)
// myForm.result.value = percentageCalculator()
fieldset { margin-top: 1em;
}
label {
display: inline-block; width: 8em; text-align: left;
}
input {
font-size: .8em; text-align: left; display: inline-block; width: 8em;
}
output::before {
content: '';
}
output {
font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
}
<h2>Percentage Calculator</h2>
<form action="" id="my-form">
<fieldset>
<legend>Calculate Percentage :</legend>
<append>What is <input type="number" name="percent" step=any min=0> % of </append>
<label><input type="number" class="amount" step=any min=0></label>
</fieldset>
<fieldset><br>
<legend>Result :</legend>
<output name="result" value='0'></output>
<br><br>
<button type="reset">Reset Calculator!</button>
</fieldset>
</form>
If it is possible for you to modify HTML template then you can add name attribute to the amount input as well then you can get the element with myForm.inputName..
Alternative solution: https://codepen.io/Maniraj_Murugan/pen/KKpdgXo
Use oninput as I did below. Also give the amount input field a name. it's missing in the OP.
// Percentage Calculator
const myForm = document.getElementById('my-form');
myForm.oninput = () => {
myForm.result.value = percentageCalculator(myForm.amount.value, myForm.percent.value);
}
function percentageCalculator(amount, percent) {
return ((percent * amount) / 100).toFixed(2)
}
fieldset { margin-top: 1em;
}
label {
display: inline-block; width: 8em; text-align: left;
}
input {
font-size: .8em; text-align: left; display: inline-block; width: 8em;
}
output::before {
content: '';
}
output {
font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
}
<h2>Percentage Calculator</h2>
<form action="" id="my-form">
<fieldset>
<legend>Calculate Percentage :</legend>
<append>What is <input type="number" name="percent" step=any min=0> % of </append>
<label><input type="number" name="amount" class="amount" step=any min=0></label>
</fieldset>
<fieldset><br>
<legend>Result :</legend>
<output name="result" value='0'></output>
<br>
<button type="reset">Reset Calculator!</button>
</fieldset>
</form>
Pass the parameters into the function as a local scope and return the result back.
function percentageCalculator(amount,percent) {
return ((percent *amount) / 100).toFixed(2)
}
myForm.result.value = percentageCalculator()
// Percentage Calculator
const calculatedResult = document.getElementById('result');
function mySubmitFunction(e) {
e.preventDefault();
const percent = document.getElementById('percent').value;
const amount = document.getElementById('amount').value;
calculatedResult.value = percentageCalculator(amount,percent);
return false;
}
function percentageCalculator(amount,percent) {
return ((percent *amount) / 100).toFixed(2)
}
fieldset { margin-top: 1em;
}
label {
display: inline-block; width: 8em; text-align: left;
}
input {
font-size: .8em; text-align: left; display: inline-block; width: 8em;
}
output::before {
content: '';
}
output {
font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
}
<h2>Percentage Calculator</h2>
<form action="" onsubmit="return mySubmitFunction(event)" id="my-form">
<fieldset>
<legend>Calculate Percentage :</legend>
<append>What is <input type="number" id="percent" name="percent" step=any min=0> % of </append>
<label><input type="number" id="amount" class="amount" step=any min=0></label>
</fieldset>
<fieldset><br>
<legend>Result :</legend>
<output id="result" name="result" value='0'></output>
<br><br>
<button type="submit">Calculate!</button>
</fieldset>
</form>
Your mistake:
Submit button instead of reset
Prevent default once it's submitted
reference element using ID

Javascript - I can not see the result of the sum of values

I have a design problem in the script that gives me the values ​​of the right column (ignoring the values ​​on the left), and the result of the sume I can not see in the green box when I click on "View Result"
// Old script
/*window.sumInputs = function() {
var inputs = document.getElementsByTagName('input'),
result = document.getElementById('total'),
sumar = 0;
for(var i=0; i<inputs.length; i++) {
var ip = inputs[i];
if (ip.name && ip.name.indexOf("total") < 0) {
sumar += parseInt(ip.value) || 0;
}
}
result.value = sumar;
}*/
// ========================
// New script
$(document).ready(function() {
var valores = $('#derecha').children();
var suma = 0;
$.each(valores, function() {
valor = $(this).val() || 0;
suma += parseInt(valor);
});
//console.log(suma);
valores = document.getElementById('total');
});
body p {
margin: 0 20px
}
/*#izquierda {display:none}*/
#izquierda,
#derecha {
display: inline-block;
vertical-align: top;
width: 140px;
margin: 20px 20px 20px 20px;
padding: 10px;
border: 1px solid #000
}
#izquierda span,
#derecha span,
body span {
font-weight: bold
}
#izquierda p,
#derecha p {
margin: 5px auto 15px;
text-align: center
}
input {
width: 80px;
display: block;
margin: 5px auto;
padding: 2px 0;
background: #f2f2f2;
border: none;
border: 1px solid #000;
text-align: center
}
#cont-resultado {
text-align: center;
width: 120px;
padding-left: 40px
}
#cont-resultado input {
display: inline-block;
margin: 0 auto 10px;
background: red;
color: #fff;
border: none;
padding: 10px 0
}
#cont-resultado a {
display: inline-block;
text-decoration: none;
color: #fff;
background: green;
padding: 10px 12px
}
#total {
display: block
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="izquierda">
<p><span>DIV LEFT</span><br>display="none"</p>
<input name="qty1" value="240">
<input name="qty2" value="862">
<input name="qty3" value="911">
<input name="qty4" value="">
<input name="qty5" value="">
<input name="qty6" value="">
<input name="qty7" value="">
<input name="qty8" value="">
</div>
<!-- ================ -->
<div id="derecha">
<p><span>DIV RIGHT</span><br>display="block"</p>
<input name="qty1" value="2">
<input name="qty2" value="2">
<input name="qty3" value="2">
<input name="qty4" value="">
<input name="qty5" value="">
<input name="qty6" value="">
<input name="qty7" value="">
<input name="qty8" value="">
</div>
<!-- ================ -->
<div id="cont-resultado">
<input name="total" id="total">
See total
</div>
<br>
<p>What I am looking for is that only the RIGHT column is sumed, ignoring the values in the left column. <br><br><span>The result of example (6) must be seen in the red box...</span></p>
What am I doing wrong...?
Thanks in advance!
$(document).ready(function(){
var valores = $('#derecha').children();
var suma = 0;
$.each(valores,function(){
valor = $(this).val() || 0;
suma += parseInt( valor );
});
//console.log(suma);
valores = document.getElementById('total');
});
You're not doing anything with suma, further, use a selector for the children .children('input').
$(document).ready(function() {
function sumInputs(e) {
e.preventDefault();
var valores = $('#derecha').children('input');
var suma = 0;
$.each(valores, function() {
valor = $(this).val();
suma += Number(valor);
});
valores = document.getElementById('total');
$(valores).val(suma);
}
$('#sumup').on('click', sumInputs);
});
body p { margin: 0 20px}/*#izquierda {display:none}*/#izquierda,#derecha { display: inline-block; vertical-align: top; width: 140px; margin: 20px 20px 20px 20px; padding: 10px; border: 1px solid #000}#izquierda span,#derecha span,body span { font-weight: bold}#izquierda p,#derecha p { margin: 5px auto 15px; text-align: center}input { width: 80px; display: block; margin: 5px auto; padding: 2px 0; background: #f2f2f2; border: none; border: 1px solid #000; text-align: center}#cont-resultado { text-align: center; width: 120px; padding-left: 40px}#cont-resultado input { display: inline-block; margin: 0 auto 10px; background: red; color: #fff; border: none; padding: 10px 0}#cont-resultado a { display: inline-block; text-decoration: none; color: #fff; background: green; padding: 10px 12px}#total { display: block}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div id="izquierda"> <p><span>DIV LEFT</span><br>display="none"</p> <input name="qty1" value="240"> <input name="qty2" value="862"> <input name="qty3" value="911"> <input name="qty4" value=""> <input name="qty5" value=""> <input name="qty6" value=""> <input name="qty7" value=""> <input name="qty8" value=""></div><!-- ================ --><div id="derecha"> <p><span>DIV RIGHT</span><br>display="block"</p> <input name="qty1" value="2"> <input name="qty2" value="2"> <input name="qty3" value="2"> <input name="qty4" value=""> <input name="qty5" value=""> <input name="qty6" value=""> <input name="qty7" value=""> <input name="qty8" value=""></div><!-- ================ --><div id="cont-resultado"> <input name="total" id="total"> <a id='sumup' href="#">See total</a></div><br><p>What I am looking for is that only the RIGHT column is sumed, ignoring the values in the left column. <br><br><span>The result of example (6) must be seen in the red box...</span></p>
You need to set the value of valores (the new one) to suma:
valores.val(suma);

How to change the color of a specific box when it isn't filled out correctly

I'm trying to create checks to validate the input of a user, such as whether he filled it out and is it the correct input. I want it to highlight the fields that contain an error.
I already asked and I was told to create a class however I don't know how to do that.
There is also
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Form Validation</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="styles/styles.css">
<link rel="stylesheet" type="text/css" href="styles/forms.css">
<script type="text/javascript">
window.onload=init;
var form;
function init() {
form = document.getElementById('testform');
form.addEventListener("submit", checkSubmit, false);
form.addEventListener("reset", checkReset, false);
form['colour'].addEventListener("change", checkSubmit, false);
form['name'].focus();
}
String.prototype.trim=function() {
return this.replace(/^\s+1\s+$/g, '');
}
function whichButton(name) {
var buttons=document.getElementsByName(name);
for (var i in buttons) {
if(buttons[i].checked) return buttons[i].value
}
return false;
}
function showOtherColour() {
document.getElementById('othercolour').style.visibility=
form['colour'].value=='other' ? 'visible' : 'hidden';
}
function checkSubmit() {
error = new Array();
//Fill the array with the error value
form['name'].value=form['name'].value.trim();
form['email'].value=form['email'].value.trim();
form['town'].value=form['town'].value.trim();
form['state'].value=form['state'].value.trim();
form['postcode'].value=form['postcode'].value.trim();
form['dob'].value=form['dob'].value.trim();
form['height'].value=form['height'].value.trim();
//Check required fields
if(!form['name'].value)
error.push('Missing Name');
if(!form['email'].value)
error.push('Missing Email Address');
if(!form['password'].value)
error.push('Missing Password');
//Check valid email address
var pattern=/^[a-zA-Z0-9._%-]+#[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,4})$/;
if(!form['email'].value.match(pattern))
error.push('Invalid Email Address');
//Check State
//Check Post Code has 4 digits
var pattern=/^\d{4}$/;
if(!form['postcode'].value.match(pattern))
error.push('Invalid Post Code');
//Check password matches confirmation
//var password = ;
/*
if(!form['passwordConfirm'].value.match(password)){
error.push("Passwords don't match");
}*/
console.log(form['confirm'].value);
console.log(form['password'].value);
if(!form['confirm'].value.match(form['password'].value)){
error.push('Passwords do not match');
}
//passwords is too short
if (!form['password'].value.length < 4) {
error.push("Password is too short (Minimum 4 characters)");
}
//height is not a number
if (isNaN(Number(form['height'].value))) {
error.push("Height is not a number");
}
//Check that one Gender item is selected
if(whichButton('gender')===false)
error.push('Please choose a Gender');
//Check that "Other" field is filled
if (!form['colour'].value ||
(form['colour'].value=='other' && !form['othercolour'].value))
error.push('Colour is not selected');
if(error.length) { // if there are errors
alert(error.join("\n"))
return false;
}
else return true;
//return confirm("This will submit the form"); //Temporary placeholder
}
function checkReset() {
return confirm("This will clear the form data");
}
</script>
<style type="text/css">
body,td,th {
font-size: 0.9em;
}
</style>
</head>
<body>
<div id="body">
<h1>Form Validation</h1>
<form action="http://test.miform.net" method="post" id="testform">
<fieldset>
<label>Name<br><input type="text" name="name" class="wide"></label>
<label>Email Address<br><input type="text" name="email" class="wide"></label>
</fieldset>
<fieldset>
<label>Address<br><input type="text" name="street" class="wide"></label>
<label>Town<br><input type="text" name="town" class="narrow"></label>
<label>State<br><input type="text" name="state" class="narrow"></label>
<label>PostCode<br><input type="text" name="postcode" class="narrow"></label>
</fieldset>
<fieldset>
<label>Password<br><input type="password" name="password" class="medium"></label>
<label>Confirm Password<br><input type="password" name="confirm" class="medium"></label>
</fieldset>
<fieldset>
<label>Date of Birth<br><input type="text" name="dob" class="medium"></label>
<label>Height<br><input type="text" name="height" class="medium"></label>
</fieldset>
<fieldset>
<legend>Gender</legend>
<label><input type="radio" name="gender" value="f">Female</label>
<label><input type="radio" name="gender" value="m">Male</label>
</fieldset>
<fieldset>
<label>Colour
<select name="colour">
<option value="">Select...</option>
<option value="black">Black</option>
<option value="white">White</option>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="cyan">Cyan</option>
<option value="magenta">Magenta</option>
<option value="yellow">Yellow</option>
<option value="other">Other</option>
</select>
</label>
<input type="text" id="othercolour">
</fieldset>
<input type="reset" name="reset" value="Clear Form">
<input type="submit" name="send" value="Send Off">
</form>
</div>
</body>
</html>
The CSS (form.css):
body {
font-family: sans-serif;
font-size: .9em;
}
form {
width: 26em;
}
label {
font-weight: bold;
float: left;
}
input.wide {
padding: .125em;
width: 25.125em;
}
input.medium {
padding: .125em;
width: 12em;
}
input.narrow {
padding: .125em;
width: 8em;
}
#othercolour {
visibility: hidden;
}
The style.css
body {
font-family: sans-serif;
font-size: .9em;
background-color: rgb(166, 183, 183);
color: black;
}
div#body {
width: 30em;
margin: auto;
padding: 1em 2em;
background-image: url(background.png);
background-repeat: repeat-x;
background-color: rgb(224, 230, 230);
}
h1,h2 {
color: rgb(47, 79, 79);
}
h2 {
margin: .25em 0em .25em 0em;
}
a {
text-decoration: none;
color: rgb(132, 156, 156);
color: white;
font-weight: bold;
}
a:hover {
color: yellow;
}
td, th {
vertical-align: top;
text-align: left;
}
img {
border: 0px;
}
p, .clear {
qclear: both;
}
#catalog {
float: left;
width: 50%;
}
#content {
float: right;
width: 46%;
}
#cart {
border: 1px solid #cccccc;
padding: 0em .5em;
}
#cart form {
display: inline;
}
#cart input.text {
width: 2em;
text-align: right;
}
#welcome {
}
#navigation {
}
#navigation span {
color: rgb(131, 155, 155);
}
#navigation ul {
list-style: none;
padding: 0;
margin: 0;
}
#navigation li {
float: left;
background-color: pink;
border-bottom: solid 1px;
}
#navigation li a {
display: block;
width: 8em;
text-decoration: none;
font-weight: bold;
text-align: center;
padding: .25em;
background-color: rgb(97, 124, 124);
}
#navigation li a:hover {
background-color: rgb(47, 79, 79);
}
You can set the input's CSS border-color property to highlight the field.
var input = document.querySelector('input'),
form = document.querySelector('form');
form.addEventListener('submit', function(e){
e.preventDefault();
if(!input.value.trim()){//if value of input is empty
input.style.borderColor = "red";
} else {
input.style.borderColor = "green";
}
});
<form>
<input placeholder="Enter something">
<br/>
<button>Validate</button>
</form>
If you use the HTML5 validation attributes, then all you’ll need is to set up a CSS rule using the :invalid pseudo class:
:invalid { . . . }
To add a class, use JavaScript's classList.add() function.
Example
function check() {
var element = document.getElementById("input");
if (element.value != "") {
document.write("Valid!");
} else {
element.classList.add("invalid");
}
}
.invalid {
background-color: rgba(255,0,0,.7);
color: white;
}
.invalid::placeholder {
color: white;
}
<input type="text" placeholder="Type Something..." id="input">
<button onclick="check();">Check</button>

Radio input as a div

In the snippet below you will see that I am styling a radio button to look like a button. I am wanting these buttons to work just as the radio button would in its normal state. Right now both radio buttons are taking on the active class from my javascript on page load. This should only happen if they are selected.
Also, the fadeToggle from the if-statement that produces the extra input under the radio buttons is functioning as if the radio buttons are checkboxes. I have to click on the same button twice to de-activate it. I think this is based on the issue above.
Does anyone have any ideas what I am doing wrong?
var rsvpAns = $('.radioTransform');
rsvpAns.click(function() {
$('.radio', this).prop('checked', !$('.radio', this).prop('checked')).change();
var radioCheck = $('.radio', this).val();
$('.radioTransform', this).toggleClass('active');
console.log(radioCheck);
if (radioCheck == 'Yes') {
$('#ansYes').fadeToggle(400);
}
});
.radio {
display: none;
}
#pushR {
margin-right: 25px;
}
.radioTransform {
width: 220px;
display: inline-block;
vertical-align: top;
background: #dbc8ca;
cursor: pointer;
padding: 15px 0;
}
.radioTransform.active {
background: red;
}
.radioAnswer {
font-family: 'Open Sans', sans-serif;
font-size: .9rem;
text-align: center;
}
#ansYes {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="rsvpForm">
<div class="formField">
<div class="radioTransform" id="pushR">
<span class="radioAnswer">YES</span>
<input type="radio" value="Yes" class="radio">
</div>
<div class="radioTransform">
<span class="radioAnswer">NO</span>
<input type="radio" value="No" class="radio">
</div>
</div>
<div class="formField" id="ansYes">
<label class="label">How are you doing?</label>
<input type="text" class="input">
</div>
<input type="submit" value="Submit RSVP" id="submit">
</form>
You don't need Javascript at all for this - only some intelligent CSS and a slight restructuring of your markup. This change will even increase the semantic value and accessibility of your solution.
I have only added Javascript for some console.logging so you see the snippet works.
Please note that in order to make radio buttons work like expected, they need to share the name attribute, otherwise both can be "on".
const radios = Array.from(document.querySelectorAll('[name="yesno"]'))
for (const radio of radios) {
radio.addEventListener('change', function() {
value.textContent = document.querySelector('[name="yesno"]:checked').value
})
}
.radio {
display: none;
}
.radioAnswer {
width: 220px;
display: inline-block;
vertical-align: top;
background: #dbc8ca;
cursor: pointer;
padding: 15px 0;
transition-duration: .4s;
position: relative;
}
.radioAnswer::before {
display: inline-block;
content: "";
border-width: 0 2px 2px 0;
border-color: transparent;
border-style: solid;
width: 0;
height: 0;
transition: width .4s linear .1s,
height .2s linear 1.6s;
position: absolute;
left: 10px;
top: 50%;
transform: rotate(35deg) translateY(-50%);
transform-origin: center right;
}
input[type=radio]:checked+.radioAnswer {
background: #0a0;
color: #fff;
}
input[type=radio]:checked+.radioAnswer::before {
border-color: #fff;
transform: rotate(35deg) translateY(-50%);
height: 1.5em;
width: .8em;
transition: all .4s linear 0s, width .4s linear .1s, height .2s linear .3s
; position: absolute;
}
.radioAnswer {
font-family: 'Open Sans', sans-serif;
font-size: .9rem;
text-align: center;
}
<input type="radio" value="Yes" class="radio" name="yesno" id="yes">
<label class="radioAnswer" for="yes">Yes</label>
<input type="radio" value="No" class="radio" name="yesno" id="no">
<label class="radioAnswer" for="no">NO</label>
<p>Selected Value: <strong id="value"></strong></p>
Your if condition block only works when you clicked yes button. Then what if you clicked No, for this condition you can have else statement. And here in this code radioTransform div don't have active class on load.
var rsvpAns = $('.radioTransform');
rsvpAns.click(function() {
$('.radio', this).prop('checked', !$('.radio', this).prop('checked')).change();
var radioCheck = $('.radio', this).val();
console.log(radioCheck);
$(this).toggleClass('active');
if (radioCheck == 'Yes') {
$('#ansYes').fadeToggle(400);
if($(this).next('.radioTransform').hasClass('active')){
$(this).next('.radioTransform').removeClass('active');
}
} else {
$('#ansYes').fadeOut(400);
if($(this).prev('.radioTransform').hasClass('active')){
$(this).prev('.radioTransform').removeClass('active');
}
}
});
.radio {
display: none;
}
#pushR {
margin-right: 25px;
}
.radioTransform {
width: 220px;
display: inline-block;
vertical-align: top;
background: #dbc8ca;
cursor: pointer;
padding: 15px 0;
}
.radioTransform.active {
background: red;
}
.radioAnswer {
font-family: 'Open Sans', sans-serif;
font-size: .9rem;
text-align: center;
}
#ansYes {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="rsvpForm">
<div class="formField">
<div class="radioTransform" id="pushR">
<span class="radioAnswer">YES</span>
<input type="radio" value="Yes" class="radio">
</div>
<div class="radioTransform">
<span class="radioAnswer">NO</span>
<input type="radio" value="No" class="radio">
</div>
</div>
<div class="formField" id="ansYes">
<label class="label">How are you doing?</label>
<input type="text" class="input">
</div>
<input type="submit" value="Submit RSVP" id="submit">
</form>
In order to achieve the toggling effect of the radio button with the backgrounds, $('.radioTransform', this).toggleClass('active'); will not be enough.
First, taking into consideration it is already inside a click handler which is attached to $('.radioTransform'), when you add this as second argument of $('.radioTransform', this).toggleClass('active'); you are telling it to look for .radioTransforms inside a .radioTransform, cause you are setting .radioTransform as the context of the selector, that's why it does not change color. And even if you remove this, you would be toggling the class for every .radioTransform there is (how many times did I write radioTransform?:) )
Second, remove background: red from .radioTransform when it is not active, else you will never see it happen
var rsvpAns = $('.radioTransform');
rsvpAns.click(function() {
$('.radio', this).prop('checked', !$('.radio', this).prop('checked')).change();
var radioCheck = $('.radio', this).val();
$(this).toggleClass('active');
$(this).siblings('.radioTransform').toggleClass('active', !$(this).hasClass('active'));
console.log(radioCheck);
if (radioCheck == 'Yes') {
$('#ansYes').fadeToggle(400);
} else {
$('#ansYes').fadeOut(400);
}
});
.radio {
display: none;
}
#pushR {
margin-right: 25px;
}
.radioTransform {
width: 220px;
display: inline-block;
vertical-align: top;
background: #dbc8ca;
cursor: pointer;
padding: 15px 0;
}
.radioTransform {
/*background: red;*/
}
.radioAnswer {
font-family: 'Open Sans', sans-serif;
font-size: .9rem;
text-align: center;
}
#ansYes {
display: none;
}
.radioTransform.active {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="rsvpForm">
<div class="formField">
<div class="radioTransform" id="pushR">
<span class="radioAnswer">YES</span>
<input type="radio" value="Yes" class="radio">
</div>
<div class="radioTransform">
<span class="radioAnswer">NO</span>
<input type="radio" value="No" class="radio">
</div>
</div>
<div class="formField" id="ansYes">
<label class="label">How are you doing?</label>
<input type="text" class="input">
</div>
<input type="submit" value="Submit RSVP" id="submit">
</form>

Categories