How to code radio group for alerts with Javascript - javascript

I currently have a question within my HTML and a radio group with a simple yes or no. I would like to make it so that when the user answers yes, they get an alert that says good job. and when they answer no, the alert says try again and reloads the page.
Here is the html
<div id="enterText"></div>
<img src="../img/Window1.jpg" width="500" height="300"><br>
<input type="radio" name="radio-group1" value="Yes">Yes
<input type="radio" name="radio-group1" value="No">No<br><br>
<button id="submitBtn">Submit</button>
and here is the current javascript I have
if (document.title === "Level 3"){
document.getElementById("enterText").innerHTML = "Look at the Picture below, Is it possible for the equation to be true?";
document.getElementById("submitBtn").addEventListener("click", calcChoices, false);
}
function calcChoices(){
var radioGroup = document.getElementsByName("radio-group1");
for (var i = 0; i < radioGroup.length; i++) {
if (radioGroup[i].checked){
console.log("You clicked: "+ radioGroup[i].value);
}
}
if(radioGroup[i].value="Yes"){
alert("NICE!")
}
if(radioGroup[i].value="No"){
alert("try again!")
}
}

Try the following code for your javascript:
document.getElementById("enterText").innerHTML = "Look at the Picture below, Is it possible for the equation to be true?";
document.getElementById("submitBtn").addEventListener("click", calcChoices, false);
function calcChoices(){
var radioGroup = document.getElementsByName("radio-group1");
for (var i = 0; i < radioGroup.length; i++) {
if (radioGroup[i].checked) {
if(radioGroup[i].value==="Yes"){
alert("NICE!")
}
if(radioGroup[i].value==="No"){
alert("try again!")
}
}
}
}

I modified your code, I found a couple of things wrong. Your first if statement was not returning true so I added a title. Your last two if statements, I joined them together. Those two if statements where not in your for loop. and I fixed some common Boolean and semicolons errors. Here is the finalalised result:
if (document.title === "Level 3") {
document.getElementById("enterText").innerHTML = "Look at the Picture below, Is it possible for the equation to be true?";
document.getElementById("submitBtn").addEventListener("click", calcChoices, false);
}
function calcChoices() {
var radioGroup = document.getElementsByName("radio-group1");
for (var i = 0; i < radioGroup.length; i++) {
if (radioGroup[i].checked) {
console.log("You clicked: " + radioGroup[i].value);
if (radioGroup[i].value === "Yes") {
alert("NICE!");
break;
} else {
alert("Try Again!");
break;
}
}
}
}
<head>
<title>Level 3</title>
</head>
<body>
<div id="enterText"></div>
<img src="../img/Window1.jpg" width="500" height="300">
<br>
<input type="radio" name="radio-group1" value="Yes">Yes
<input type="radio" name="radio-group1" value="No">No
<br>
<br>
<button id="submitBtn">Submit</button>
</body>

This code will reload the page if they say no. Also, fixed minor bugs that said that the choice was YES every time.
if (document.title === "Level 3"){
document.getElementById("enterText").innerHTML = "Look at the Picture below, Is it possible for the equation to be true?";
document.getElementById("submitBtn").addEventListener("click", calcChoices, false);
}
function calcChoices(){
var radioGroup = document.getElementsByName("radio-group1");
for (var i = 0; i < radioGroup.length; i++) {
if (radioGroup[i].checked){
console.log("You clicked: "+ radioGroup[i].value);
if(radioGroup[i].value==="Yes"){
alert("NICE!");
}
if(radioGroup[i].value==="No"){
alert("try again!");
location.reload(); //Added this line
}
}
}
}

Related

How to check if the user input exist in an Array?

Is there a way to check if an user input from text box (for example) exists in an array that I created and imported from other JS files?
And can I link all that code to an HTML button?
In Python to do this I use "in":
if a in List:
print("That's In")
PS: I know that List in Python are a little different with Arrays in JavaScript.
From my platform's JavaScript documentation:
//Use:
if (in_array('a', ['a','b',4,'z'])) {console.log('item in array.');}
//Prerequisite functions:
function in_array(s,a)
{
var r = false;
if (is_array(a))
{
for (var i = 0; i<a.length; i++)
{
if (a[i]==s) {r = true;}
}
}
else {console.log('Error: object to in_array ('+a+') is not an array.');
}
return r;
}
function is_array(a)
{
return ((a.constructor.toString().indexOf('Array') > 0) ? true : false);
}
Thanks for all, i think that i resolved my problem with array.indexOf
There's my solution below
How can i close the post ?
<!DOCTYPE html>
<form id="form" onsubmit="return false;">
<input style="position:absolute" type="text" id="userInput" /> <br>
<input style="position:absolute;" type="submit" onclick="name();" /> <br>
<script type="text/javascript">
function name() {
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
var input = document.getElementById("userInput").value;
//Check if a value exists in the data1 array
if(fruits.indexOf(input) !== -1){
document.write(input, " Value exists!");
document.write(" Press F5 to reload")
} else{
document.write(input, " Value does not exists!");
document.write(" Press F5 to reload");
}
}
</script>
</form>
</html>

javascript quiz : Display random options

I just coded a html quiz page... Here is My Javascript Code
<SCRIPT language="JavaScript" type="text/javascript">
function checkAnswer(quizForm,
theAnswer,
){
var s = "?";
var i = 0;
for(;i<quizForm.elements.length;i++)
{ if(("cc" ==
quizForm.elements[i].name) &&
(quizForm.elements[i].checked)) {
s = quizForm.elements[i].value; } }
if("?" == s)
{ document.getElementById("demo").innerHTML = "Please Click Answer";
return false; }
if(s == theAnswer)
{
document.getElementById("demo").innerHTML = "Very Good";
}
else
{
document.getElementById("demo").innerHTML = "Please Check Ur Answer";
}
return false;
}
</SCRIPT>
and my html code is
What is JavaScript?
<FORM method="POST"
onSubmit="return checkAnswer(this,'B');"
>
<INPUT TYPE="RADIO" VALUE="A" NAME="cc">
A. Another name for Java<BR>
<INPUT TYPE="RADIO" VALUE="B" NAME="cc">
B. A scripting language mostly for the web<BR>
<INPUT TYPE="RADIO" VALUE="C" NAME="cc">
C. When you use Java without compiling<BR>
<INPUT TYPE="SUBMIT" VALUE="Submit Answer">
<p id="demo"></p>
I want to add my options (A,B,C,D) in Javascript code. which can randomly display options and also when user click right answer it shows 'Correct else Wrong
To randomize the question, you need to store your question in an array or object. Then, when you show the question, you just need to show the randomized version of the question:
let questions = [
{
questions: ["Options 1", "Option 2", "Option 3", "option 4"],
answer: "Option 2",
},
]
let randomizeArray = (arr) =>{
let Question = [],
till = arr.length;
while(Question.length != till){
if(arr.length === 1){
Question[Question.length] = arr.splice(0, 1)[0];
}else{
let random = Math.floor(Math.random()*(arr.length));
Question[Question.length] = arr.splice(random, 1)[0];
}
}
return Question;
}
Here, randomizeArray alawys return the randomize array.
You need to show user the randomized version of the question.
Then, when user selects an answer, you need to compare it with the answer. And show user the associative answer.
I think you get the idea.

Validate form: if radio button is not checked show error message Javascript

I am trying to show an error message if the checkboxes are unchecked.
My solution doesn't work. Please see below. Not sure how to check this.
<input type="radio" name="comm">Yes
<input type="radio" name="comm">No
<div id="error_message"></div>
<button id="btn">Submit</button>
document.getElementById("btn").addEventListener("click", function(event){
event.preventDefault();
myFunction();
});
function myFunction() {
var errortxt = "";
var radios = document.getElementsByName('comm');
for(var i = 0; i < radios.length; i++) {
if (radios[i].checked = false) {
errortxt = "Error text";
} else {
errortxt = "";
}
}
document.getElementById("error_message").innerHTML = "<p>" + errortxt + "</p>";
}
You made a mistake but you were on the good way of thinking, i did update your snippet with the correct synthax.
= is for assigning a value to a variable in javascript.
There are two operators for comparing values in JavaScript: strict equality === and “normal” (or lenient) equality == .
see http://2ality.com/2011/06/javascript-equality.html
for(const radio of radios){
if(!radio.checked){
errortxt = "Error text";
break; // this will break the loop when a radio is not checked (will save precious time !)
}
}
document.getElementById("btn").addEventListener("click", function(event){
event.preventDefault();
myFunction();
});
function myFunction() {
var errortxt = "";
var radios = document.getElementsByName('comm');
for(const radio of radios){
if(!radio.checked){
errortxt = "Error text";
break;
}
}
document.getElementById("error_message").innerHTML = "<p>" + errortxt + "</p>";
}
<input type="radio" name="comm">Yes
<input type="radio" name="comm">No
<div id="error_message"></div>
<button id="btn">Submit</button>
simply using required in HTML can fix this issue
like this :
<input type="radio" name="comm" required>

How to put IF CONDITION with an AND CONDITION and the NOT OPERATOR in javascript?

<body>
<input type="radio" name="other_charges" value="To Pay" >To Pay
<input type="radio" name="other_charges" value="COD" >COD
<input type="submit" onclick="sum_cash()"/>
</body>
here is my html ...in this i am having two radio buttons with different values and i have called a function using onclick event....here is the code...
<script type="text/javascript">
function sum_cash() {
var elements_ocharges = document.getElementsByName('other_charges');
for (var i = 0; i < elements_ocharges.length; i++) {
if (elements_ocharges[i].checked)
value_ocharges = elements_ocharges[i].value;
}
var val_ocharges=value_ocharges;
if (val_ocharges=="To Pay") {
alert("pay");
}
if (val_ocharges=="COD") {
alert("cod");
}
if ((val_ocharges!="COD") && (val_ocharges!="To Pay") ) {
alert("hi");
}
}
</script>
Now in the function, I am checking the value of the radio button selected. If the user chooses the Pay radio button then on clicking the submit button it alerts the user for payment. When the user chooses the COD radio button then on submitting it alerts COD.
What I want is that when the user has selected nothing and clicked on the submit button then it should alert the user. Unfortunately, it is not checking the condition. Can anyone please help me?
You may try like this:
<script type="text/javascript">
function sum_cash()
{
var elements_ocharges = document.getElementsByName('other_charges');
var value_ocharges = null;
for (var i = 0; i < elements_ocharges.length; i++)
{
if (elements_ocharges[i].checked)
value_ocharges = elements_ocharges[i].value;
}
var val_ocharges=value_ocharges;
if(val_ocharges=="To Pay")
{
alert("pay");
}
else if(val_ocharges=="COD")
{
alert("cod");
}
else
{
alert("hi");
} }
</script>
your problem is this conditional near the top:
if (elements_ocharges[i].checked)
value_ocharges = elements_ocharges[i].value;
since neither radio button is checked, value_ocharges is never set. this will cause an error when you attempt to access the value with var val_ocharges=value_ocharges; you should set the value of value_ocharges to something (null is fine) before entering your loop, then everything will work:
<script type="text/javascript">
function sum_cash()
{
var elements_ocharges = document.getElementsByName('other_charges');
var value_ocharges = null;
for (var i = 0; i < elements_ocharges.length; i++)
{
if (elements_ocharges[i].checked)
value_ocharges = elements_ocharges[i].value;
}
var val_ocharges=value_ocharges;
if(val_ocharges=="To Pay")
{
alert("pay");
}
if(val_ocharges=="COD")
{
alert("cod");
}
if ((val_ocharges!="COD") && (val_ocharges!="To Pay") )
{
alert("hi");
}
}
</script>
Try this ,
else if ((val_ocharges =="")
{
alert("hi");
}
Hope this helps!!
First, set your value_ocharges above the for loop:
var value_ocharges = false;
Then, instead of:
if ((val_ocharges!="COD") && (val_ocharges!="To Pay") ) {
alert("hi");
}
use this outside of the loop:
if (!val_ocharges){
alert("hi");
}
Basically, this checks if val_ocharges is defined somewhere in the loop, and if it's not, it triggers the alert.

getting validation to check boxes

Hello all: I recently stumbled upon a question about form validation, which I'm currently trying to get working. I got the code from an answer and then customized it to more what I'm needing.:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function Validate(){
if(!validateForm()){
alert("Something happened");
return false;
}
return true
}
function validateForm()
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked){return true}
}
}
return false;
}
</script>
</head>
<body>
<form name="myForm" action="http://upload.wikimedia.org/wikipedia/commons/3/30/Googlelogo.png" onsubmit="return Validate()" method="get">
<input type="checkbox" name="live" value="yesno">You are alive.
<br>
<input type="checkbox" name="type" value="person">You are a person.
<br>
<input type="checkbox" name="eyes" value="color">Your eyes have color.
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
NOTE: The image is just from a Google Image Search, and is on Wikipedia (I do not own it).
Now, when I originally entered the HTML from the answer into the Tryit Editor at W3 Schools, it would give me a "Something Happened" alert, or do nothing. (I think that's what is was supposed to do).
Still, (now that I have my own questions) it will say "something happened" if nothing is selected, but no matter how many check (over 1 checked) it will just give me the image. Basically, what I want is it to check if ALL or ONLY SOME are checked. If all are checked i want one image, and if only some, I want a different one.
I hope this isn't too confusing, and I appreciate any help :)
P.S.:Here is the question where I got the code: Original Question
Try this for the script section, it will change the form's "action" attribute (which points the form to a the desired URL upon submitting) after validating how many checkboxes are checked:
<script type="text/javascript">
function Validate(formRef){
var checkboxes = getCheckboxes(formRef);
var checkedCount = validateForm(checkboxes);
if(checkedCount == checkboxes.length){
// All are checked!
return true;
} else if(checkedCount > 0) {
// A few are checked!
formRef.setAttribute('action', 'http://upload.wikimedia.org/wikipedia/commons/thumb/2/24/Yahoo!_logo.svg/200px-Yahoo!_logo.svg.png');
return true;
} else {
alert("Something happened");
}
return true;
}
function getCheckboxes(formRef) {
var c = formRef.getElementsByTagName('input');
var checkboxes = [];
for (var i = 0; i<c.length; i++){
if (c[i].type == 'checkbox')
{
checkboxes.push(c[i]);
}
}
return checkboxes;
}
function validateForm(checkboxes) {
var checkedCount = 0;
for (var i = 0; i < checkboxes.length; i++){
if (checkboxes[i].checked){
checkedCount++;
}
}
return checkedCount;
}
</script>
The form HTML should be updated to pass "this", the reference to the form object being validated, into the Validate() function, to avoid the need to query for it again:
<form name="myForm" action="http://upload.wikimedia.org/wikipedia/commons/3/30/Googlelogo.png" onsubmit="return Validate(this)" method="get">
Try this (will alert first option if one or more but less than 3 checked, will alert second option if exactly 3 checked):
<!DOCTYPE html>
<html>
<body>
<input type="checkbox" name="live" value="yesno">You are alive.
<br>
<input type="checkbox" name="type" value="person">You are a person.
<br>
<input type="checkbox" name="eyes" value="color">Your eyes have color.
<br>
<input value="Submit" type="submit" onclick="
var count = 0;
for(var i = 0; i < document.getElementsByTagName('input').length - 1; i++)
{
if(document.getElementsByTagName('input')[i].checked)
{
count += 1;
}
}
if(count >= 1 && count < 3)
{
alert('First Option');
}else
{
if(count == 3)
{
alert('Second Option');
}
}" />
</body>
</html>
The following should get you on the right path:
function Validate() {
var checkboxes = processCheckboxes();
if (checkboxes.all.length == checkboxes.checked.length) {
alert("All are checked");
} else if (checkboxes.checked.length > 0) {
alert("Some checked");
} else {
alert("None checked");
}
return false;
}
function processCheckboxes() {
var checkboxes = document.querySelectorAll('input[type=checkbox]');
var checked = [].filter.call( checkboxes, function( el ) {
return el.checked
});
return { all: checkboxes, checked: checked };
}
You can then process the checked boxes in whatever manner you like before submitting.
See a working example here: http://jsfiddle.net/jkeyes/Zcu7d/

Categories