If else condition issue - javascript

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.

Related

get array of checkboxes checked, and only if seletced in a specific order, then go to URL

First time asking here. I tried a number of topics for this, and I currently use a code for checkboxes, but it's for gathering into a mailform and sending to me via php. I can't seem to find exactly what I need for the following scenario.
I am reworking some Flash puzzles to be all html and javascript (or jquery). One puzzle requires the player to enter a code (to open a safe). In Flash they clicked buttons with code symbols on them, so I thought, Checkboxes displayed as images could work...
I have 9 checkboxes. Each has a value from 1 to 9. In the layout they are mixed up (they are not positioned on the page in sequential order) and I use images to represent the checkboxes.
I want to find out if all the boxes are selected, and if they are selected in the exact order of 1-9.
If the checkboxes are checked in the correct order according to their value (1,2,3,4,5,6,7,8,9) then on clicking the Submit button, the player is taken to the next webpage.
I can also do this with names or Ids, whatever works. Or php. I was hoping to keep it simple, because I am not savvy with the javvy. I probably know enough to be dangerous to myself and others :)
Thanks in advance for any help, or links to a topic that could point me in the right direction.
Here's my html code.
<form name="checklist" method="post" action="My-Page.php">
<label>
<input type="checkbox" value="8">
<img src="btn_8.png"></label>
<label>
<input type="checkbox" value="3">
<img src="btn_3.png"></label>
<label>
<input type="checkbox" value="9">
<img src="btn_9.png"></label>
<label>
<input type="checkbox" value="2">
<img src="btn_2.png"></label>
<label>
<input type="checkbox" value="5">
<img src="btn_5.png"></label>
<label>
<input type="checkbox" value="4">
<img src="btn_4.png"></label>
<label>
<input type="checkbox" value="7">
<img src="btn_7.png"></label>
<label>
<input type="checkbox" value="1">
<img src="btn_1.png"></label>
<label>
<input type="checkbox" value="6">
<img src="btn_6.png"></label>
<input type="submit" value="Open">
</form>
Here's the js I found that gets the values, but I don't know how to make it get the values in that specific order, and then go to a URL, or alert the user to an error.
var array = []
var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')
for (var i = 0; i < checkboxes.length; i++) {
array.push(checkboxes[i].value)
}
Update. I struggled with this, and finally asked a friend to help. What took me 8 days, he did in like 1 hour, from scratch.
I do appreciate those who took time to give me some hints, and this site is great for learning.
As you didn't share code , I will not help you fix it. I can give you some hints and you can try to implement that.
Call onClick function on each checkbox selection.
Create an array and push the selected checkbox's values into it.
// example: checkedArr = [1,2,3,4];
maintain a final order of values with another array
// expectedArr = [1,2,3,4];
Deep compare those 2 arrays and depending on their result, proceed with your business logic.
Comparing two array with their order
var is_same_arr = (checkedArr.length == expectedArr.length) && checkedArr.every(function(element, index) {
return element === expectedArr[index];
});
Here is one way to do it in JavaScript. You maintain a selected array that you either add to or remove items from as the checkboxes are clicked. Then, when the form is submitted, you do a couple checks: first you see if all boxes have been checked. Next, you see if all of the numbers in the selected array are in order.
const form = document.querySelector("#form");
let selected = [];
const numberOfCheckboxes = document.querySelectorAll("#form input").length;
form.addEventListener("click", function(e) {
if (e.target.nodeName !== "INPUT") return;
if (e.target.checked) {
selected.push(parseInt(e.target.value));
} else {
selected = selected.filter(el => el != e.target.value);
}
})
function check(e) {
console.log(selected);
if (selected.length !== numberOfCheckboxes) {
e.preventDefault();
alert("You didn't select all the boxes");
}
const inOrder = selected.every((el, i, arr) => i === 0 || el === arr[i-1] + 1);
if (!inOrder) {
e.preventDefault();
alert("Wrong order!");
}
}
<form id="form" onsubmit="return check(event)">
<label>
<input type="checkbox" value="1" /> 1
</label>
<label>
<input type="checkbox" value="2" /> 2
</label>
<label>
<input type="checkbox" value="3" /> 3
</label>
<button>submit</button>
</form>

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('')"
>

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.");
}
}

Javascript Checkbox Validation not Checking if Ticked

I've looked through a lot of the questions that people have already asked on this, but I cannot find a solution that has helped me.
I'm a beginner to programming so know little about what to do, I have four check boxes and to submit the form, you have to select at least one of them, but no message comes up and the form is able to be submitted without one of the boxes being ticked.
This is my code below:
<tr>
<td align="right">
<label for="erdbeersocken"><p>Erdbeersocken<sup>*</sup>:</label>
<br>
<label for="armstulpen">Armstulpen<sup>*</sup>:</label>
<br>
<label for="cupcakes">Cupcakes<sup>*</sup>:</label>
<br>
<label for="babykleidung">Babykleidung<sup>*</sup>:</label>
<br>
</td>
<td align="left">
<form action="../" onsubmit="return checkCheckBoxes(this);">
<input type="CHECKBOX" name="CHECKBOX_1" value="Erdbeersocken">
<br>
<input type="CHECKBOX" name="CHECKBOX_2" value="Armstulpen">
<br>
<input type="CHECKBOX" name="CHECKBOX_3" value="Cupcakes">
<br>
<input type="CHECKBOX" name="CHECKBOX_4" value="Babykleidung">
<br>
<input type="SUBMIT" value="Submit!">
</td>
</tr>
</form>
<script type="text/javascript" language="JavaScript">
<!--
function checkCheckBoxes(theForm) {
if (
theForm.CHECKBOX_1.checked == false or
theForm.CHECKBOX_2.checked == false or
theForm.CHECKBOX_3.checked == false or
theForm.CHECKBOX_4.checked == false)
{
alert ('You didn\'t choose any of the checkboxes!');
return false;
} else {
return true;
}
}
//-->
</script>
Which looks like: Text here (Checkbox here)
I'm using Notepadd++ more advanced code does not seem to work, so if anyone could help me with simplified JavaScript, I would really appreciate it. :)
function checkCheckBoxes(theForm) {
if ($("input[type='checkbox']:checked").length){
return true;
}else{
alert ('You didn\'t choose any of the checkboxes!');
return false;
}
}
For your form, you should give all the checkboxes the same name but give each checkbox a different value -- this will create an array for your checkboxes (see note at bottom of response if you don't yet know what an array is):
<input type="CHECKBOX" name="CHECKBOX" value="Erdbeersocken">
<br>
<input type="CHECKBOX" name="CHECKBOX" value="Armstulpen">
<br>
<input type="CHECKBOX" name="CHECKBOX" value="Cupcakes">
<br>
<input type="CHECKBOX" name="CHECKBOX" value="Babykleidung">
then in your confirm submit function you want to use a for loop with two nested if statements to check if a checkbox has been checked. I'll give you an example of some code I recently did:
var interestsSelected = false;
for (var i = 0; i < document.forms[0].interests.length; ++i ) {
if (document.forms[0].interests[i].checked == true) {
interestsSelected = true;
break;
//code gives go ahead for submission because at least one checkbox has been checked
}
}
if (interestsSelected !=true) {
window.alert("You must select at least one hobby or interest");
return false;
//code Woot woot woot! It all works!
}
This was my form section for the checkboxes:
<input type="checkbox" name="interests" value="technology" />Technology <br />
<input type="checkbox" name="interests" value="arts" />The Arts <br />
<input type="checkbox" name="interests" value="music" />Music <br />
<input type="checkbox" name="interests" value="film" />Movies <br/>
<input type="checkbox" name="interests" value="shopping" />Shopping <br />
<input type="checkbox" name="interests" value="outdoor" />Camping <br />
<input type="checkbox" name="interests" value="garden" />Gardening <br />
As a fellow beginner :) I often find it useful if everything is spelled out in as simple a language as possible so I'm going to provide some details here that you might or might not already know.
Anytime you create a form, an array for the form is automatically created (you won't see it listed anywhere, the browser will automatically create one when it accesses the form data BUT you can (should) refer to it in your coding). So if you have one form on your page you will have an array forms[0], if you have two different forms on your page then the first form will have an array forms[0] and the second form will have an array forms[1], each containing all of the elements in the respective forms.
If you name all your checkboxes the same name, you are essentially creating an array within an array -- the big Mama Bear array is forms[0] and nestled inside her is the Baby Bear array (your checkbox name[]).
In order to reference the Baby Bear array, you have to acknowledge the Mama Bear array first: that is why in the code example I gave above, you see "document.forms[0]" (the Mama Bear array) followed by ".interests[i]" (the Baby Bear array).
Hope this helps :)
HTML for my example
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p>Select a box</p>
<form id="aform">
<input type="checkbox">
<input type="checkbox">
</form>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="test.js"></script>
</body>
</html>
And the javascript in its own file (always seperate code from css and from html)
window.onload=function() {
$("#aform").change(function () {
alert('a box is checked');
})
};

Enable/disable a form element after checking radio button checked states

I have ten or so questions with radio buttons. They all need to be set to true, before a user can move on to another level. If and only if these ten questions have be answered to true, I'd like to have one of the elements on the form be enabled for further editing. This, I can do on the server side, but don't know how to do it in JavaScript. Any help? Much appreciated. Thanks.
<div>
<label> First Question:</label>
<label>
<input checked="checked" class="radio_buttons optional pull-right allowed" id="is_complete_and_works_true" name="project[person_attributes][is_complete_and_works]" type="radio" value="true" />Yes</label>
<label >
<input class="radio_buttons optional pull-right allowed" id="is_complete_and_works_false" name="project[person_attributes][is_complete_and_works]" type="radio" value="false" />No</label>
</div>
<div>
<label> Second Question:</label>
<label>
<input checked="checked" class="radio_buttons optional pull-right allowed" id="is_complete_and_works_true" name="project[person_attributes][researched]" type="radio" value="true" />Yes</label>
<label >
<input class="radio_buttons optional pull-right allowed" id="is_complete_and_works_false" name="project[person_attributes][researched]" type="radio" value="false" />No</label>
</div>
<div>
<label> Third Question:</label>
<label>
<input checked="checked" class="radio_buttons optional pull-right allowed" id="is_complete_and_works_true" name="project[person_attributes][is_complete_and_works]" type="radio" value="true" />Yes</label>
<label >
<input class="radio_buttons optional pull-right allowed" id="is_complete_and_works_false" name="project[person_attributes][is_complete_and_works]" type="radio" value="false" />No</label>
</div>
This code extends to several more of questions.
I've been able to select radios by doing so:
var first_ten = $(':radio[name="project[person_attributes][is_complete_and_works]"][value=true], :radio[name="project[person_attributes][researched]"][value=true], etc…);
Now, I have no idea how to iterate over each and when I click on each radio, whether yes or no, I'd like to see the result for the element to be enabled. Any thoughts much appreciated.
Something like the following will do the job:
<script type="text/javascript">
function proceed(form) {
var el, els = form.getElementsByTagName('input');
var i = els.length;
while (i--) {
el = els[i];
if (el.type == 'checkbox' && !el.checked) {
form.proceedButton.disabled = true;
return;
}
}
form.proceedButton.disabled = false;
}
</script>
<form onclick="proceed(this);">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="submit" name="proceedButton" disabled>
</form>
Note that this is considered bad design as if javascript is not available or enabled, the user can never click the button. Better to deliver the form in a useful state and the, when submitted, use script to validate that the buttons are all checked and cancel the submit if they aren't.
Then at the server you can also check the state and only show the next page if the current one passes validation. If it doesn't, return the user to the first page.
That way neither you or the user care if the script works or not, the page still functions. Of course it might be a better experience if the script does work, but at least the choice isn't binary and it also gives you a simple fallback to support a very wide array of browsers with minimal effort.
So a better solution is:
<form onsubmit="reurn validate(this);" ...>
...
</form>
Then in the function:
function validate(form) {
// if validateion fails, show an appropriate message and return false,
// if it passes, return undefined or true.
}
And always validate at the server since you really have no idea what happened on the client.
Edit
Form controls don't need a name and ID, just use a name. In a radio button set, only one control can be checked, you can't check all of them.
It seems to me that what you are trying to do is to see if at least one radio button has been checked in each set. You can do that based on the code above and selecting each set as you encounter it, e.g.
function validateForm(form) {
// Get all the form controls
var control, controls = form.elements;
var radios = {};
var t, ts;
// Iterate over them
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
// If encounter a radio button in a set that hasn't been visited
if (control.type == 'radio' && !radios.hasOwnProperty(control.name)) {
ts = form[control.name];
radios[control.name] = false;
// Check the set to see if one is checked
for (var j=0, jLen=ts.length; j<jLen; j++) {
if (ts[j].checked) {
radios[control.name] = true;
}
}
}
}
// Return false if any set doesn't have a checked radio
for (var p in radios) {
if (radios.hasOwnProperty(p)) {
if (!radios[p]) {
alert('missing one');
return false;
}
}
}
}
</script>
<form onsubmit="return validateForm(this);">
<input type="radio" name="r0">
<input type="radio" name="r0">
<br>
<input type="radio" name="r1">
<input type="radio" name="r1">
<br>
<input type="reset"><input type="submit">
</form>
Note that your form should include a reset button, particularly when using radio buttons.

Categories

Resources