Having problems understanding checked radio buttons - javascript

I'm trying to validate my form through JavaScript and instead of manually checking each radio button I decided to loop through a group of radio buttons and check to see if they were checked or not.
I'm simply trying to see if a group of radio buttons is checked or not. But the problem I'm facing is. It's returning both true and false when I check either of them. If I don't check either, they both return false but if I check one, it returns true and false.
Here is my code:
function validateForm(){
let firstliGroup = document.getElementsByName("yesnocheck");
for(i=0; i<firstliGroup.length; i++){
//console.log(firstliGroup[i].checked);
if(firstliGroup[i].checked == true){
console.log('success');
return true;
}
else {
console.log('failed');
return false;
}
}
}
<form name="driverkeylistform" method="post" onsubmit="return validateForm()">
<fieldset id="group1">
<input type="radio" name="yesnocheck" value="Yes"><span>Yes</span>
<input type="radio" name="yesnocheck" value="No"><span>No</span>
</fieldset>
<input type="submit" value="Send">
</form>

Try this:
function getRadioValue(name) {
let elements = document.getElementsByName(name);
for (let i = 0; i < elements.length; i++) {
if (elements[i].checked) {
return elements[i].value;
}
}
return null;
}
function validateForm() {
var yesnocheck = getRadioValue("yesnocheck");
console.log(yesnocheck);
return false;
}
If nothing is checked, then getRadioValue function will return null.
If any option was checked, it will return it's value.

Try using document.forms[0].yesnocheck.
function validateForm()
{
return (document.forms[0].yesnocheck.value.length > 0 &&
document.forms[0].yesnoremote.value.length > 0 &&
document.forms[0].yesnocable.value.length > 0 &&
document.forms[0].condition.value.length > 0);
}
<form name="driverkeylistform" method="post" onsubmit="return validateForm()">
<fieldset id="group1">
<input type="radio" name="yesnocheck" value="Yes"><span>Yes</span>
<input type="radio" name="yesnocheck" value="No"><span>No</span>
</fieldset>
<label for="gateremote">Gate remote batteries checked?:</label>
<input type="radio" name="yesnoremote" value="Yes"><span>Yes</span>
<input type="radio" name="yesnoremote" value="No"><span>No</span>
<label for="internetcabletv">Internet and Cable TV checked?:</label>
<input type="radio" name="yesnocable" value="Yes"><span>Yes</span>
<input type="radio" name="yesnocable" value="No"><span>No</span>
<label for="unitcondition">Unit Condition?:</label>
<input type="radio" name="condition" value="clean"><span>Clean</span>
<input type="radio" name="condition" value="light"><span>Light</span>
<input type="radio" name="condition" value="heavy"><span>Heavy</span>
<input type="radio" name="condition" value="superheavy"><span>SuperHeavy</span>
<input type="submit" value="Send">
</form>

Related

Link Radiobox button to Input

I have 2 radio button, each valued Yes and No respectively and 1 textbox.. If I checked on No button, the input textbox will open. If checked on Yes, textbox will disabled.
This code is working fine but I want to delete content that input to the textbox if the user checked Yes
function ismcstopu() {
var chkNo = document.getElementById("radio2_ismcstop");
var mcnostopreason = document.getElementById("mcnostopreason");
mcnostopreason.disabled = chkNo.checked ? false : true;
if (!mcnostopreason.disabled) {
mcnostopreason.focus();
} else {
mcnostopreason.val('');
}
}
<input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" onclick="ismcstopu()" value="Yes">Yes
<input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" onclick="ismcstopu()" value="No">No
<label for="mcnostopreason">If No, Reason:</label>
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
.val is a jQuery construct but you are using DOM
Here is a better version using eventListener
Change the document.getElementById("container") to whatever container you have (your form for example)
Note: It is often better to test true than to test false
I also added labels to the radios so we can click the yes or no too
document.getElementById("container").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.name === "ismcstop") {
const mcnostopreason = document.getElementById("mcnostopreason");
mcnostopreason.disabled = tgt.value === "Yes";
if (mcnostopreason.disabled) {
mcnostopreason.value = '';
} else {
mcnostopreason.focus();
}
}
})
<div id="container">
<label><input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" value="Yes">Yes</label>
<label><input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" value="No">No</label>
<label for="mcnostopreason">If No, Reason:
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
</label>
</div>
jQuery version
$("[name=ismcstop]").on("click", function() {
if (this.name === "ismcstop") {
const $mcnostopreason = $("#mcnostopreason");
$mcnostopreason.prop("disabled", this.value === "Yes");
if ($mcnostopreason.is(":disabled")) {
$mcnostopreason.val("");
} else {
$mcnostopreason.focus();
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" value="Yes">Yes</label>
<label><input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" value="No">No</label>
<label for="mcnostopreason">If No, Reason:
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
</label>
mcnostopreason is not a jQuery object. therefore you could do: var mcnostopreason = $("#mcnostopreason");
Or you could just change mcnostopreason.val('') to mcnostopreason.value = '' ( this will mean you don't need to change anything else)

JavaScript Function to validate checkbox

I'm trying to not allow both checkboxes to be checked at the same time. Here is my vanilla JS. I have the function already validating to return true when one is checked and false when neither are checked. Radio boxes are not an option.
function valForm() {
var both = document.getElementById("cEmail1" & "cPhone1");
for (var i = 1; i <= 2; i++) {
if (document.getElementById("cEmail1").checked) {
return true;
} else if (document.getElementById("cPhone1").checked) {
return true;
} else if (both.checked) {
return false;
} else {
return false;
}
}
}
<form action="http://severien.com/grit/formecho.php" method="post" name="contactUsForm" onsubmit="return valForm()">
<span class="box3"><label for="cEmail" class="l5" >Contact me by email</label>
<input class="check1" id="cEmail1" type="checkbox" name="contactbyemail" /></span>
<span class="box4"><label for="cPhone" class="l6">Contact me by phone</label>
<input class="check2" id="cPhone1" type="checkbox" name="contactbyphone" /></span> <br />
<div class="formSubmit"><input type="submit" value="Submit" /></div>
</form>
If radio boxes really aren't an option, then there are a few issues with your code. First of all, you are checking if each of the boxes is checked, and if either of them is checked, then you are immediately returning. The second, and much larger problem, is that your both element should be undefined. The & in JavaScript is a bitwise operator, and getElementById should only return one element. Instead, you could implement the equivalent of a logical XOR like so:
function valForm(){
return document.getElementById("cEmail1").checked != document.getElementById("cPhone1").checked;
}
You can't get two elements at the same time using getElementById, so you'll need to check them separately by using the && operator.
You also need to check this first, because the two if statements before this will preempt this check.
function valForm() {
var cEmail = document.getElementById("cEmail1");
var cPhone1 = document.getElementById("cPhone1");
if (cEmail.checked && cPhone1.checked) {
console.log("false");
return false;
} else if (cEmail.checked || cPhone1.checked) {
console.log("true");
return true;
} else {
console.log("false");
return false;
}
}
<form action="http://severien.com/grit/formecho.php" method="post" name="contactUsForm" onsubmit="return valForm()">
<span class="box3"><label for="cEmail" class="l5" >Contact me by email</label>
<input class="check1" id="cEmail1" type="checkbox" name="contactbyemail" /></span>
<span class="box4"><label for="cPhone" class="l6">Contact me by phone</label>
<input class="check2" id="cPhone1" type="checkbox" name="contactbyphone" /></span> <br />
<div class="formSubmit"><input type="submit" value="Submit" /></div>
</form>
This should return false if neither or both are checked:
function valForm() {
var email = document.getElementById("cEmail1");
var phone = document.getElementById("cPhone1")
if (email.checked && !phone.checked || !email.checked && phone.checked) {
console.log('ok')
return true;
}
console.log('no ok')
return false;
}
<form action="http://severien.com/grit/formecho.php" method="post" name="contactUsForm" onsubmit="return valForm()">
<span class="box3"><label for="cEmail" class="l5" >Contact me by email</label>
<input class="check1" id="cEmail1" type="checkbox" name="contactbyemail" /></span>
<span class="box4"><label for="cPhone" class="l6">Contact me by phone</label>
<input class="check1" id="cPhone1" type="checkbox" name="contactbyphone" /></span> <br />
<div class="formSubmit"><input type="submit" value="Submit" /></div>
</form>
</div>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.slectOne').on('change', function() {
$('.slectOne').not(this).prop('checked', false);
$('#result').html($(this).data( "id" ));
if($(this).is(":checked"))
$('#result').html($(this).data( "id" ));
else
$('#result').html('Empty...!');
});
});
</script>
</head>
<body>
<input type="checkbox" class="slectOne" data-id="1 selected"/>
<input type="checkbox" class="slectOne" data-id="2 selected"/>
<input type="checkbox" class="slectOne" data-id="3 selected"/>
<input type="checkbox" class="slectOne" data-id="4 selected"/>
<input type="checkbox" class="slectOne" data-id="5 selected"/>
<input type="checkbox" class="slectOne" data-id="6 selected"/>
<input type="checkbox" class="slectOne" data-id="7 selected"/>
<input type="checkbox" class="slectOne" data-id="8 selected"/>
<input type="checkbox" class="slectOne" data-id="9 selected"/>
<input type="checkbox" class="slectOne" data-id="10 selected"/>
<span id="result"></span>
</body>
</html>
here is a good example to use as well
https://www.w3schools.com/code/tryit.asp?filename=FB6JK5HW3Z53

form JavaScript function checkAnswer not loading pages

I have a form that I've been working on for a school project and I can't figure out what's wrong with the JavaScript checkAnswer function. The form and all the buttons work, but when I hit the submit button, all that loads is a blank page. I have tried researching forms but I can't figure out where my code is wrong. Why won't it check anything?
Here is the form from my index.html file:
<script src="CheckForm.js"></script>
<form method="post" action="return checkAnswer(this, '1', 'Correct.html',
'Incorrect.html');" name="quizForm" id="quizForm">
<input type="radio" name="choice" value="1"/>
<script>getMusician(answer1);</script><br/>
<input type="radio" name="choice" value="2"/>
<script>getMusician(answer2);</script><br/>
<input type="radio" name="choice" value="3"/>
<script>getMusician(answer3);</script><br/>
<input type="radio" name="choice" value="4"/>
<script>getMusician(answer4);</script><br/>
<input type="submit" value="Submit"/>
</form>
This is the code from my CheckForm.js file:
function checkAnswer(quizForm, Answer, CorrectPage, IncorrectPage)
{
var i = 0;
var j = null;
for(;i<quizForm.elements.length();i++)
{
if(quizForm.elements[i].value.checked)
j = quizForm.elements[i].value;
}
if(j === null)
{
windows.alert("Please make a selection.");
return false;
}
if(j == Answer)
{
document.location.href = CorrectPage;
}
else
{
document.location.href = IncorrectPage;
}
return false;
}
You shouldn't need a form for this. It looks like you are creating a static site so I would remove the form and the rest you are pretty close with. Here is a working example for you.
Also it looks like you are creating some sort of quiz site. Be aware users can use the developer console to see the correct answer (the first input to checkAnswer() method)- I thought it would be worth mentioning that.
function checkAnswer(answer, correctPage, incorrectPage) {
var i = 0;
var j = null;
var inputs = document.getElementsByClassName('musician');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked)
j = inputs[i].value;
}
if (j == null) {
alert("Please make a selection.");
return false;
}
if (j == answer) {
console.log('CORRECT!')
document.location.href = CorrectPage;
} else {
console.log('incorrect :(')
document.location.href = IncorrectPage;
}
}
<div id="inputContainer">
<input type="radio" name="choice" class="musician" value="1" />musician 1
<br/>
<input type="radio" name="choice" class="musician" value="2" />musician 2
<br/>
<input type="radio" name="choice" class="musician" value="3" />musician 3
<br/>
<input type="radio" name="choice" class="musician" value="4">musician 4
<br/>
</div>
<input type="button" onclick="checkAnswer('1', 'Correct.html',
'Incorrect.html')" value="Submit" />

Making javascript check what radio form has been selected

I am trying to make a dog race.
Basically what I want is to check what radio the user checked,
compare it to a random number between 1 - 5 and see if he won.
My question is... How do I compare them?
This is my code so far.
function chooser(){
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
document.getElementById("winner").innerHTML = rand;
if(pick == rand)
{document.getElementById("winner").innerHTML =("win!");}
else {
document.getElementById("winner").innerHTML =("loose");
}
}
HTML:
<form id="pick" action="rand">
<input type="radio" name="dog" id="dog1">Dog1<br>
<input type="radio" name="dog" id="dog2">Dog2<br>
<input type="radio" name="dog" id="dog3">Dog3<br>
<input type="radio" name="dog" id="dog4">Dog4<br>
<input type="radio" name="dog" id="dog5">Dog5<br>
</form>
<br>
<br>
<input type="submit" value="Gamble" onclick="chooser();">
<br>
<p id="winner"> </p>
A jQuery and Native JavaScript Approach. Take your pick.
$("#submitjq").click(function() {
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
var pick = $("input[type=radio][name='dog']:checked").val();
if(pick == rand)
{
$("#winner").html("jQuery: Won!");
}
else {
$("#winner").html("jQuery: Lost!");
}
});
document.getElementById('submitjs').onclick = function () {
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
var pick = document.pick.dog.value;
console.log(pick);
if(pick == rand)
{
document.getElementById("winner").innerHTML = "JavaScript: Won!" ;
}
else {
document.getElementById("winner").innerHTML = "JavaScript: Lost!" ;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="pick" name="pick" action="rand">
<input type="radio" name="dog" value="dog1">Dog1<br>
<input type="radio" name="dog" value="dog2">Dog2<br>
<input type="radio" name="dog" value="dog3">Dog3<br>
<input type="radio" name="dog" value="dog4">Dog4<br>
<input type="radio" name="dog" value="dog5">Dog5<br>
</form>
<br>
<br>
<input type="submit" id="submitjs" value="Gamble Native JavaScript" />
<input type="submit" id="submitjq" value="Gamble jQuery" />
<br>
<p id="winner"> </p>
You need to give each radio button a value, and then getElementsByName, iterating through to find the one that's checked. See similar thread...

Creating a multiple choice option in javascript

I have created an HTML multiple choice question. I am facing a problem how to validate it. Below is the HTML code:
<h1>JavaScript is ______ Language.</h1><br>
<form>
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button>Submit Answer</button>
When the user clicks the submit button, there should be an alert that will show a message based on what was selected.
If no option was selected, the alert box should say "please select choice answer".
If the "Scripting" option was selected, the alert box should say "Answer is correct !"
If an option different from "Scripting" is selected, the alert box should say "Answer is wrong".
I want to create this validation in JavaScript.
You have to use onclick attribute and more js
attach event hander to your button
get radio elements value
compare
var submitAnswer = function() {
var radios = document.getElementsByName('choice');
var val= "";
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
if (val == "" ) {
alert('please select choice answer');
} else if ( val == "Scripting" ) {
alert('Answer is correct !');
} else {
alert('Answer is wrong');
}
};
<h1>JavaScript is ______ Language.</h1><br>
<form >
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button onclick="submitAnswer()">Submit Answer</button>
var submitAnswer = function() {
var radios = document.getElementsByName('choice');
var val= "";
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
if (val == "" ) {
alert('please select choice answer');
} else if ( val == "Scripting" ) {
alert('Answer is correct !');
} else {
alert('Answer is wrong');
}
};
<h1>JavaScript is ______ Language.</h1><br>
<form >
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button onclick="submitAnswer()">Submit Answer</button>
Some changes
I made some changes to the code above to make it more 'abstract'
<h1>JavaScript is ______ Language.</h1><br>
<form id="d1">
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button onclick="submitAnswer(d1.choice.value, 'Scripting')">Submit Answer</button>
<script>
var submitAnswer = function(valore, rightanswer) {
if (valore == rightanswer) {
alert("OK");
}
};
</script>
Another, more complex example
<div style="background-color:lightblue">
<h1>JavaScript is a <span id='a1'>______</span> Language.</h1><br>
<form id="d1">
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
<br>
<input type="submit" value="submit" onclick="validate(choice.value, 'Scripting', 'd1','a1')">
</form>
</div>
<div style="background-color:lightblue">
<h1>Python is a <span id='a2'>______</span> Language.</h1><br>
<form id="d2">
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Wonderful"> Wonderful
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
<br>
<input type="submit" value="submit" onclick="validate(choice.value, 'Wonderful', 'd2', 'a2')">
</form>
</div>
<script>
var validate = function(valore, rightanswer, form, span) {
var formname = document.getElementById(form)
var spanname = document.getElementById(span)
spanname.innerHTML = rightanswer;
if (valore == rightanswer) {
formname.innerHTML ="<div style='background-color:lightgreen'><h1>GREAT! YOU'RE RIGHT: The answer, in fact, was: " + rightanswer + "</h1></div>";
}
else {
formname.innerHTML ="<div style='background-color:pink'><h1>Sorry, you where wrong: The answer was: " + rightanswer + "</h1></div>";
}
};
</script>
Use the required keyword. This prompts the user to choose a value, when the submit button is pressed without choosing any option. And always prefer to use
<input type="submit" value="submit"> over <button>Submit Answer</button>
while handling forms. Use the onclick() event handler to call your Javascript code.
<h1>JavaScript is ______ Language.</h1><br>
<form >
<input type="radio" name="choice" value="Scripting" required> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
<input type="submit" value="submit" onclick="validate()">
</form>
And the javascript part is as follows.
<script type="text/javascript">
function validate() {
var a= document.getElementByName("choice");
for (var i = 0, i < a.length; i++) {
if (a[i].checked) {
if( a[i].value == "scripting" )
alert("your answer is correct");
else
alert("your answer is not correct");
break;
} } }
</script>
Here condition is showing in alert pop up box. but I want to show it in a html tag.
But after clicking submit button, innerHTML content showing a millisecond and then automatic remove the content. How selection will stay in innerHTML
document.getElementById("answer").innerHTML;
var submitAnswer = function() {
var radios = document.getElementsByName('choice');
var val= "";
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
if (val == "" ) {
document.getElementById("answer").innerHTML = "please select choice answer";
} else if ( val == "Scripting" ) {
document.getElementById("answer").innerHTML = "Answer is correct !"
} else {
document.getElementById("answer").innerHTML = "Answer is wrong"
}
};
You can add a function and event onClick so that whenever someone clicks on option submit button will appear.

Categories

Resources