Beginner - form validations - HTML CSS Javascript class not working - javascript

I'm wrapping up a final project for my online coding class, but having trouble with validations.
https://codepen.io/allisonmw/pen/WNgQmKM
In my form, employees are selecting what color uniform color they'd like, what shifts they'd prefer and what types of uniforms they'd prefer to wear. All of these need to include validation. I'm not sure how to validate the checkboxes or the ratio buttons. Can someone help provide guidance? I want to make sure atleast 1 checkbox has been selected and the radio button is not left blank. I'm also not able to figure out how to validate a color has been selected outside of 0,0,0 (black)
<span class="formfields">Color Selection</span>
<input onblur="validatecolor()" class="forminputs" type="color" id="colorselection" required>
<span class="formreply" id="replycolor"></span>
<br>
<span class="formfields" >Shift Preferences </span> <br>
<input onclick="validateshift()" class="forminputs" type="checkbox" id="shift"
value="first_shift"> First Shift <br>
<input onclick="validateshift()" class="forminputs" type="checkbox" id="shift"
value="second_shift"> Second Shift <br>
<input onclick="validateshift()" class="forminputs" type="checkbox" id="shift"
value="third_shift"> Third Shift <br>
<span class="formreply" id="replyShift"></span>
<br>
<span class="formfields" >Uniform Top</span> <br>
<input onclick="validatetop()" class="forminputs Atype" type="radio" name="top" id="longsleeve" value="long_sleeve" > Long Sleeve <br>
<input onclick="validtop()" class="forminputs Atype" type="radio" name="top" id="shortsleeve" value="short_sleeve"> Short Sleeve <br>
<br>
<span class="formfields" >Uniform Bottom</span> <br>
<input onclick="validatebottom()" class="forminputs Atype" type="radio" name="bottom" id="Pants" value="pants" > Pants <br>
<input onclick="validatebottom()" class="forminputs Atype" type="radio" name="bottom" id="Shorts" value="shorts"> Shorts <br>
function validatecolor(){
if(document.querySelector("#colorselection").value.length==0){
document.querySelector("#replycolor").innerHTML="Select a Color";
return false;
}
else{
document.querySelector("replycolor").innerHTML="thank you!";
return true;
}
}
function validateshift(){
if(document.querySelector("#shift").value.length==0){
document.querySelector("#replyShift").innerHTML="Select a Shift";
return false;
}
else{
document.querySelector("#replyShift").innerHTML="Thank You!";
return true;
}
}
function validatetop(){
if(document.querySelector("#top").value.length==0){
document.querySelector("#replytop").innerHTML="Select a top";
return false;
}
else{
document.querySelector("#replytop").innerHTML="Thank You!";
return true;
}
}
function validatebottom(){
if(document.querySelector("#bottom").value.length==0){
document.querySelector("#replybottom").innerHTML="Select a bottom";
return false;
}
else{
document.querySelector("#replybottom").innerHTML="Thank You!";
return true;
I'm currently using .value.length==0 as the default value for the color, checkbox and radio button, but it's not working. I'm getting a "thank you!" validation to show up when I click a shift preference, but I'm not able to get the "select a shift" to fire.
I'm not able to get anything fire for #colorselection, #top or #bottom

Related

How can I have the user click two Terms and Conditions before allowing them to proceed?

I'm trying to make it so that a user has to accept two terms and conditions before being able to click the "Agree and Continue" button. I tried to insert a second checkbox but then the user can just click the "Agree and Continue" button without either box being checked, so this code only has one checkbox.
Thanks!
<SCRIPT language=JavaScript>
<!--
function checkCheckBox(f){
if (f.agree.checked == false )
{
alert('Please check the box to continue.');
return false;
}else
return true;
}
//-->
</SCRIPT>
<form action="https://google.com" method="GET" onsubmit="return checkCheckBox(this)">
<!--Enter your form contents here-->
<input type="checkbox" value="0" name="agree">
<b> I Agree to the Terms and Conditions and Privacy Policy</b>
<br><br>
<b> I understand that I am accessing a third-party site and will abide by their Terms and Conditions and Privacy Policy</b><br>
<br>
<input type="submit" value="Agree and Continue">
</form>
You can make the checkbox required with:
<form>
<input type="email" required />
<input type="password" required>
<input type="checkbox" required><label for="scales">I'm agree</label>
<input type="submit">
</form>
It will generate:
You don't need any other javascript check, just the 'required' attributes.
Add a second checkbox with an explicit name and then use the boolean "or", ||, to see if both are not checked. The else isn't needed because the first condition returns so it is safe to remove.
function checkCheckBox(f) {
if (!f.agree.checked || !f.agree_third_party.checked) {
alert('Please check the box to continue.');
return false;
}
return true;
}
And alternative is to break it up so that you can give different messages:
function checkCheckBox(f) {
if (!f.agree.checked) {
alert('Please check the first box to continue.');
return false;
}
if (!f.agree_third_party.checked) {
alert('Please check the second box to continue.');
return false;
}
return true;
}
Further, you can completely remove JavaScript and use the native HTML5 required attribute. (I couldn't help wrapping the checkboxes in labels for convenience and accessibility, but they aren't required.)
<label for="agree">
<input type="checkbox" value="0" name="agree" id="agree" required>
<b> I Agree to the Terms and Conditions and Privacy Policy</b>
</label>
<br><br>
<label for="agree_third_party">
<input type="checkbox" value="0" name="agree_third_party" id="agree_third_party" required>
<b> I understand that I am accessing a third-party site and will abide by their Terms and Conditions and Privacy Policy</b><br>
</label>
And if you want to customize the message:
<input type="checkbox" value="0" name="agree" id="agree" required
oninvalid="this.setCustomValidity('You must agree to our terms and conditions.')"
oninput="this.setCustomValidity('')"
>

Want to display texts based on what radio is selected with CSS applied

So I am stuck on this past 2-3 days as I am new to this. I am making a HTML form and styling it with CSS. The texts that appear are in listed order and one of the lists has 2 radio buttons. Selecting either of them should take you to a different page showing/asking the questions that is based on the selection.
I am having problem figuring this out. How can display that text based on the selection. Here is the part of my code. I am using conditionals to know what is being selected.
function check() {
if(document.getElementById("radio_myself").checked) {
document.write("<li><label class='fs-field-label fs-anim-upper' for='q1'>What's your name?</label></li>");
}
else {
// show text;
}
}
<li data-input-trigger>
<label class="fs-field-label fs-anim-upper" for="q1">Welcome <br> <br> Is this application for yourself or someone else?</label>
<span><input onchange="check(); return false;" id="radio_myself" name="radMyself" type="radio" value="Myself"/>Myself</span>
<span><input onchange="check(); return false;" id="radio_selse" name="radSelse" type="radio" value="Someone"/>Someone Else</span>
I want it to display according to how I styled by CSS. How can I achieve this?
Like this ?
<li data-input-trigger>
<label class="fs-field-label fs-anim-upper" for="q1">Welcome <br> <br> Is this application for yourself or someone else?</label>
<span><input onchange="check(); return false;" id="radio_myself" name="radMyself" type="radio" value="Myself"/>Myself</span>
<span><input onchange="check(); return false;" id="radio_selse" name="radMyself" type="radio" value="Someone"/>Someone Else</span>
<script>
function check() {
if (document.getElementById("radio_myself").checked) {
document.getElementById("test").innerHTML = "What's your name?";
} else if (document.getElementById("radio_selse").checked) {
document.getElementById("test").innerHTML = "What's your friends name?";
}
}
</script>
<p>
<label id="test"></label>
</p>

Javascript checkbox validation: how to alert if user didn't check a particular checkbox?

So what I am doing is something like a simple medication reminder, so the system display a list of medications the user should be taking, and the user then tick the checkbox of the medicine they have taken, but what I want to do is if for example, the user only ticked Medicine One and Two, then I want an alert saying "Why you didn't take Medicine Three?" and a drop down box appears with a list of possible reasons of which the user can choose from. And if the user only took Medicine Three, the system will display alert saying "Why didn't you taken Medicine One and Two?", and drop down box appears with a list of possible reasons. And if user has ticked all three checkbox, then display an alert saying "That great! Well Done!"
<form>
<input type="checkbox" name="a" value="one">Medicine One<br>
<input type="checkbox" name="b" value="two">Medicine Two<br>
<input type="checkbox" name="c" value="three">Medicine Three<br>
<input id=xbutton type="button" onClick="validate()" value="Submit">
</form>
I know how to do validation for one checkbox (like a terms agreement checkbox), but I'm a bit confused as to how to incorporate so many validation rules into one function.
Use querySelectorAll to iterate all the checkbox elements and check the .checked property.
Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.
input[type="checkbox"]:not(:checked) will select only those elements which are not checked.
function validate() {
var msg = [];
[].forEach.call(document.querySelectorAll('input[type="checkbox"]:not(:checked)'), function(elem, index) {
msg.push(elem.name);
});
alert(msg.length ? 'Please check ' + msg.join(' and ') : 'All are checked!');
}
<form>
<input type="checkbox" name="a" value="one">Medicine One
<br>
<input type="checkbox" name="b" value="two">Medicine Two
<br>
<input type="checkbox" name="c" value="three">Medicine Three
<br>
<input id=xbutton type="button" onClick="validate()" value="Submit">
</form>
Fiddle here
Using jquery can help you to make things easy.
Here is the fiddle: https://jsfiddle.net/swaprks/zs7tpuo0/
HTML:
<form>
<input type="checkbox" name="a" value="one">Medicine One<br>
<input type="checkbox" name="b" value="two">Medicine Two<br>
<input type="checkbox" name="c" value="three">Medicine Three<br>
<input id=xbutton type="button" value="Submit">
</form>
JAVASCRIPT:
$("#xbutton").click(function(){
validate();
});
function validate(){
if ( $('input[type="checkbox"]:not(:checked)').length == 3 ) {
alert("Select atleast one option.");
}
}

How to do toggle two mutually exclusive radio buttons in HTML

I have two radio buttons. When I click on one, the other should become unchecked, and vice versa.
The code I've produced so far is not working:
<input type="radio" id="rbdemail" onclick="chekrbdclick()" checked="checked" />
<input type="radio" id="rbdsitelnk" onclick="chekrbdclick()" />
function chekrbdclick()
{
// How to manage here?
}
Simple, just use a 'name' property with the same value for both elements:
<html>
<body>
<form>
<input type="radio" name="size" value="small" checked> Small
<br>
<input type="radio" name="size" value="large"> Large
</form>
</body>
</html>
hope it helps
<form>
<label>
<input type="radio" name="size" value="small" checked> Small
</label>
<br>
<label>
<input type="radio" name="size" value="large"> Large
</label>
</form>
Give them a name attribute with common value like size, and it will work. For best practice, you can place your input tag inside a label tag, so that, even if your user clicks on the text beside the button (ie on "Small" or "Large"), the respective radio button gets selected.
The perfect answer is above answered ,but I wanna share you how it can work by javascript ,this is javascript work (not standard answer) ....
<input type="radio" id="rbdemail" onclick="chekrbdclick(0)" checked="checked" value="Small" />Small<br>
<input type="radio" id="rbdsitelnk" onclick="chekrbdclick(1)" value="Large" />Large
<script>
function chekrbdclick(n)
{
var small = document.getElementById('rbdemail');
var large = document.getElementById('rbdsitelnk');
if(n === 0){
small.checked = true;
large.checked = false;
}
else {
small.checked = false;
large.checked = true;
}
}
</script>

If else condition issue

I'm making a quiz for my website. I am checking for input on each question. The first one is simply the user's name. I got that one to work using an if else statement, what I'm trying to do now is check the radio button after the checking the textbox. So, if the user enters their name and then doesn't answer the next question an alert window pops up asking them to answer it. I'm also doing this for checkboxes and a drop down menu. Based on the color selected on the radio buttons the background of the website will change. Any help with any of the issues would be most appreciated.
JavaScript
function NameBox() {
var x = document.forms["Hogwarts"]["firstname"].value;
if (x == null || x == "") {
window.alert("Name must be filled out!");
return false;
} else {
RadioColors();
return true;
}
}
function RadioColors() {
If(document.getElementById('red' || 'blue' || 'green' || 'yellow').checked)
window.alert("Radio Selected");
else {
window.alert("Radio Not Selected");
}
}
HTML
<div id="main">
<h1>Assignment 2: Sorting Hat Quiz<h1>
<form name="Hogwarts" onsubmit= "return NameBox()" >
<fieldset>
<legend>Which Hogwarts House Are You In?</legend>
<br>
<h1>Please Enter Your First Name</h1>
<input type="text" name="firstname" value="">
<br>
<h1>What is your favorite color?</h1>
<input type="radio" name="color" value="red">Red
<br>
<input type="radio" name="color" value="blue">Blue
<br>
<input type="radio" name="color" value="green">Green
<br>
<input type="radio" name="color" value="yellow">Yellow
<br>
<h1>Which of these values do you possess?</h1>
<input type="checkbox" name="gry1" value="chivalry">Chivalry
<br>
<input type="checkbox" name="sly1" value="Cunning">Cunning
<br>
<input type="checkbox" name="huf1" value="loyalty">Loyalty
<br>
<input type="checkbox" name="rav1" value="intelligence">Intelligence
<br>
<input type="checkbox" name="gry2" value="brave">Brave
<br>
<input type="checkbox" name="sly2" value="innovative">Innovative
<br>
<input type="checkbox" name="huf2" value="patience">Patience
<br>
<input type="checkbox" name="rav2" value="logical">Logic
<br>
<input type="checkbox" name="gry3" value="confident">Confident
<br>
<input type="checkbox" name="sly3" value="Ambitious">Ambitious
<br>
<input type="checkbox" name="huf3" value="friendly">Friendly
<br>
<input type="checkbox" name="rav3" value="creative">Creative
<br>
<h1>What is your favorite animal?</h1>
<select name="animal">
<option value="selectanimal">Select an Animal</option>
<option value="snake">Snake</option>
<option value="lion">Lion</option>
<option value="raven">Raven</option>
<option value="badger">Badger</option>
</select>
<br>
<input type="submit" value="Submit">
<br>
<input type="reset" value="Reset">
</fieldset>
</form>
</div>
Unfortunately you can't simply use the following:
If (document.getElementById('red'||'blue'||'green'||'yellow').checked)
You have to split each id in to a separate bit and it would get very verbose. However JavaScript is (usually) wonderfully flexible so you can reduce the amount of code so try the following:
function id_(id) {var r = false; if (document.getElementById(id)) {r = document.getElementById(id);} return r;}
if (id_('red').checked || id_('blue').checked || id_('green').checked || id_('yellow').checked) {}
You're still calling document.getElementById though through a proxy function which is fine because it can help keep your code much less verbose. Do not change the function name from id_ to id though as it will create a mind-bogglingly horrible conflict when you use id for parameters sent to functions.
Other then that use Firebug for Firefox or any of the built in web consoles/inspectors (Chrome CTRL+SHIFT+J, IE F12 Developer tools and (real) Opera Dragonfly).
Check how you're calling document.getElementById -
Essentially, anything in the parentheses is an input to the function, and if you have operators in that input, those will be evaluated first.
In your case you're supplying:
'red'||'blue'||'green'||'yellow'
The operators in this statement are designed to return a Boolean value, ie, True or False.
'red' is a string (as are the others), and in Javascript, any string with a length greater than zero is a "truthy" value.
Since these are evaluated before being input to getElementById, what it's actually supplied is true.
You can envision it being called like this:
document.getElementById(true)
And of course you have no element named "true".
Your first port of call will, then, be to structure the logic differently, as what you want to compare is whether the element with ID 'red' is checked, OR the element with ID 'blue' is checked, etc.
Try something like
if (document.getElementById('red').checked || document.getElementById('blue').checked || document.getElementById('green').checked || document.getElementById('yellow').checked )
This way, you're comparing the results instead of supplying a boolean as input
You can't use getElementById since the radio buttons were not assigned ids. Instead, since each radio button was assigned the same name to indicate they are a part of the same radio button group, you can use getElementsByName to find all of them. Then iterate through them to determine which one is checked.
function RadioColors () {
var selectedColor;
var colors = document.getElementsByName('color');
for (var i = 0; i < colors.length; i++) {
if (colors[i].checked) {
selectedColor = colors[i].value;
}
}
if (selectedColor)
window.alert("Radio Selected");
else {
window.alert("Radio Not Selected");
}
}
Here is a jsfiddle for you to check it out in action.

Categories

Resources