I am making a form field where I would like to do a simple show-hide to display div's on a radio button.
<form id="basic" name="basic">
<label><input name="formelement" type="radio" value="yes" /> Yes </label>
<label><input name="formelement" type="radio" value="no" /> No </label>
<div id="yes" style="display: none;">
This is the div that displays that shows when 'Yes' is selected.
</div>
<div id="no" style="display: none;">
This is the div that displays that shows when 'No' is selected.
</div>
</form>
I have played with some various javascript's I have found online and have achieved not a lot of success as most of them online manage to show-hide one div. Getting the 'yes' to hide when 'no' is selected and vice-versa is the tricky part. If anyone could provide some assistance that would be really appreciated!
Just paste these code between head tags
<script type="text/javascript">
window.onload=function(){
var el1 = document.getElementsByName('formelement')[0];
var el2 = document.getElementsByName('formelement')[1];
el1.onchange=function(){
var show=el1.value;
var hide=el2.value;
document.getElementById(show).style.display='block';
document.getElementById(hide).style.display='none';
}
el2.onchange=function(){
var show=el2.value;
var hide=el1.value;
document.getElementById(show).style.display='block';
document.getElementById(hide).style.display='none';
}
}
</script>
DEMO.
The below is assuming value of radio is same as id of the div..
function getRadioVal(name){
var oRadio = document.forms[0].elements[name];
for(var i = 0; i < oRadio.length; i++)
if(oRadio[i].checked)
return oRadio[i].value;
return '';
}
//hide both divs..
document.getElementById("yes").style.display = "none";
document.getElementById("no").style.display = "none";
//show only one of them..
document.getElementById(getRadioVal("formelement")) = "block";
Dealing with javascript without any libraries is a pain when things get complex, I would recommend libraries such as jQuery
this is what you want
How can I check whether a radio button is selected with JavaScript?
assign onclick event and you are good to go.
Related
Can't uncheck radio buttons after cloning a html element. Can anyone help me with this?
I tried .reset() .remove() and .checked=false but somehow it doesn't work.
<form>
<fieldset id="firstFieldset">
<legend>An advertiser wants to know if Shopping ads will appear on YouTube. What should you tell her?</legend>
<input type="radio" id="firstQuestionFirstOption" name="firstQuestion" value="firstQuestionFirstOption"> Shopping ads can only show on pre-roll video ads on YouTube<br>
<input type="radio" id="firstQuestionSecondOption" name="firstQuestion" value="firstQuestionSecondOption">Shopping Ads can only appear on Google.com<br>
<input type="radio" id="firstQuestionThirdOption" name="firstQuestion" value="firstQuestionThirdOption">Shopping ads can appear on Google Search partner websites like YouTube<br>
<input type="radio" id="firstQuestionFourthOption" name="firstQuestion" value="firstQuestionFourthOption">Shopping Ads can only appear on retail websites<br><br>
<button type="button" onclick="checkTheAnswerToTheFirstQuestion()">Show answer</button>
<p id="answerToTheFirstQuestion" onclick="checkTheAnswerToTheFirstQuestion();"></p>
<script>
function checkTheAnswerToTheFirstQuestion() {
if (document.getElementById('firstQuestionThirdOption').checked) {
document.getElementById('answerToTheFirstQuestion').innerHTML = "The answer is true";
} else {
document.getElementById('answerToTheFirstQuestion').innerHTML = "The answer is false";
var fieldset = document.getElementById("firstFieldset");
var newFieldset = fieldset.cloneNode(true);
}
}
</script>
</fieldset>
document.body.appendChild(newFieldset) = false;
</form>
<br><br>
<input type="button" value="Start again?" onClick="location.href=location.href">
You never actually add the thing you clone to the DOM, but the .checked = false method works in my example below. I've used .disabled = true since it seems more useful to show the answer you gave in the context of the response for reviewing what you previously answered.
In case I have made a wrong assumption, I left the .checked = false part commented.
I also cleaned up some of the radio input elements, as the you can simply set the right answer to "true" instead of having to maintain unique strings for all questions and possible answers.
I also made your function to check for answer more dynamic by allowing to give it the fieldset for the question rather being tied to a particular question.
This should give you a good understanding of adding/removing elements dynamically with JavaScript the way I think you are looking for.
<html lang="en">
<head>
<style>
.answerCorrect {
color: green;
}
.answerIncorrect {
color: red;
}
</style>
</head>
<body>
<form>
<fieldset id="firstFieldset">
<legend>An advertiser wants to know if Shopping ads will appear on YouTube. What should you tell her?</legend>
<input type="radio" name="firstQuestion" value="false"> Shopping ads can only show on pre-roll video ads on YouTube<br>
<input type="radio" name="firstQuestion" value="false">Shopping Ads can only appear on Google.com<br>
<input type="radio" name="firstQuestion" value="true">Shopping ads can appear on Google Search partner websites like YouTube<br>
<input type="radio" name="firstQuestion" value="false">Shopping Ads can only appear on retail websites<br><br>
<button class="answerButton" type="button" onclick="checkTheAnswer('firstFieldset')">Answer</button>
</fieldset>
</form>
<form id="answered">
</form>
<br/>
<input type="button" value="Start again?" onClick="location.href=location.href">
<script>
function checkTheAnswer(fieldsetId) {
// get a handle on the fieldset we are checking the answer for by its ID
let fieldset = document.getElementById(fieldsetId)
// was the checked value in the field set "true" (aka - correct)
let isCorrect = fieldset.querySelector("input[type='radio']:checked").value === "true"
// clone the answered fieldset
let newFieldset = fieldset.cloneNode(true)
// unset the radio buttons in a cloned fieldset
//newFieldset.querySelector("input[type='radio']:checked").checked = false
// disable the radio buttons in the 'answered' cloned fielset
let radios = newFieldset.querySelectorAll("input[type='radio']")
radios.forEach(r => r.disabled = true)
// remove the "Answer" button in the new fieldset
let answerButton = newFieldset.querySelector("button.answerButton[type='button']")
newFieldset.removeChild(answerButton)
// show the answer in the new fieldset
let answer = document.createElement("p")
answer.classList.add("answerText")
answer.classList.add(isCorrect ? "answerCorrect" : "answerIncorrect")
let answerText = document.createTextNode(`The answer is ${isCorrect ? "correct" : "incorrect"}.`)
answer.appendChild(answerText)
newFieldset.append(answer)
// get a handle on the form section used to put the cloned/answered fielsets into
let formAnswered = document.getElementById('answered')
// append the answered/reset fieldset into the 'answered' form
formAnswered.appendChild(newFieldset)
}
</script>
</body>
I have the following code:
<fieldset id="dificuldade">
<legend>Dificuldade:</legend>
<input type="radio" name="dificuldade" value="facil"> Fácil </input>
<input type="radio" name="dificuldade" value="medio"> Médio </input>
<input type="radio" name="dificuldade" value="dificil"> Difícil </input>
</fieldset>
<fieldset id="tipo">
<legend>Tipo de jogo:</legend>
<input type="radio" name="Tipodejogo" value="somar"> Somar </input>
<input type="radio" name="Tipodejogo" value="subtrair"> Subtrair </input>
<input type="radio" name="Tipodejogo" value="dividir"> Dividir </input>
<input type="radio" name="Tipodejogo" value="multiplicar"> Multiplicar </input>
</fieldset>
<input type="button" value="Começa" id="button" ></input>
</form>
and here is the jsfiddle with both the html and the js http://jsfiddle.net/3bc9m/15/ . I need to store the values of the 2 fieldset so I, depending on the values picked can generate a game, but my javascript isn't returning any of them. What is wrong? I've been told that JQuery is much easier but i can't use it.
Your code on jsFiddle seems to be working fine for the most part. The only thing was that the elements output and output2 don't exist on the page.
So this code that was supposed to display the selected values wasn't working:
document.getElementById('output').innerHTML = curr.value;
document.getElementById('output2').innerHTML = tdj.value;
The part that actually retrieves the selected values is working fine.
Just add those two elements to the page, like this:
<p>Selected Values:</p>
<div id="output"></div>
<div id="output2"></div>
An updated jsFiddle can be found here.
EDIT
If a radio button from only one of the sets is selected, the code fails. You could use this code to find the selected values instead:
document.getElementById('button').onclick = function() {
var dif = document.getElementsByName('dificuldade');
var tip = document.getElementsByName('Tipodejogo');
var difValue;
for (var i = 0; i < dif.length; i++) {
if (dif[i].type === "radio" && dif[i].checked) {
difValue = dif[i].value;
}
}
var tipValue;
for (var i = 0; i < tip.length; i++) {
if (tip[i].type === "radio" && tip[i].checked) {
tipValue = tip[i].value;
}
}
document.getElementById('output').innerHTML = difValue;
document.getElementById('output2').innerHTML = tipValue;
};
An updated jsFiddle is here.
Consider this post that adresses the issue. It shows a few javascript methods as well as how you would use it in jQuery.
How can I check whether a radio button is selected with JavaScript?
Is there a specific reason you want to break it down by fieldset instead of directly accessing the radio buttons by name?
I have 2 radio buttons no one of them checked by default and I want if any one of them checked a Div appear according to what radio button was checked.
( Divs have different content )
and if the selection changed the one which appeared now disappear and the other appear.
and when one of them appear there are another 2 radio to do the same thing for another one div ( one to show and one to hide )
Here what I tried to do
JavaScript
function haitham()
{
if(document.getElementById('s').checked == true)
{
document.getElementById('StudentData').style.display = "block";
document.getElementById('GraduateData').style.display = "none";
}
else if(document.getElementById('g').checked == true)
{
document.getElementById('GraduateData').style.display = "block";
document.getElementById('StudentData').style.display = "none";
}
}
function info()
{
if(document.getElementById('y').checked == true)
{
document.getElementById('MoreInfo').style.display = "block";
}
else if(document.getElementById('n').checked == true)
{
document.getElementById('MoreInfo').style.display = "none";
}
}
HTML
<input class="margin2" id="s" type="radio" name="kind" value="student" onchange="haitham()"
required="required" />Student
<input class="margin2" id="g" type="radio" name="kind" value="graduate" onchange="haitham()"
required="required" />Graduate
<div id="StudentData">
content 1
<input class="margin2" id="y" type="radio" name="info" value="yes" onchange="info()"
required="required" />Student
<input class="margin2" id="n" type="radio" name="info" value="no" onchange="info()"
required="required" />Graduate
</div>
<div id="GraduateData">
content 2
</div>
<div id="MoreInfo">
content 3
</div>
the first work good but the other 2 radio did not work although it should be the same
Thank you ...
Your problem wasn't a javascript or html one, it was actually a CSS issue. Your code was fine, aside from the fact that the values for display are "none" and "block" not "" and "hidden". I modified your code and updated the fiddle.
Here's the link:
http://jsfiddle.net/8JpSQ/4/
Just add a clicked event to the radio buttons, and through a Javascript function change the attribute of the respective DIV to hidden when required. To show it instead, remove the attribute 'hidden'. Also, we'd probably be able to help more if you can post some code showing what you tried/what went wrong. But what I suggested should be the general approach to make what you want happen.
I have no idea what your HTML is, so here's what I have:
$('input[type="checkbox"]').click(function() {
$('.divWrapper > div').eq($(this).index()).fadeOut().siblings().fadeIn();
});
I'm assuming this is your structure:
<form>
<checkbox>
<checkbox>
...
</form>
<div class="divWrapper">
<div>
<div>
...
</div>
How do I use DOM in Javascript to check if a radio button is checked and then if so add new form elements to datesettings?
//Radio buttons
<input type="radio" id="dateoption" name="dateoption" value="1">
<input type="radio" id="dateoption" name="dateoption" value="2">
//Add new form elements
<span id="datesettings"></span>
Im currently reading a Javascript book but its not helping me understand. If someone could help me with this example then maybe the penny will drop. Thanks for your time.
Check out this page:
It explains the process so you understand why you're doing it a certain way, AND it gives good example code.
http://www.webdevelopersnotes.com/tips/html/finding_the_value_of_a_radio_button.php3
You would write a function to do the check, like this:
function CheckDateOptions() {
var o1 = document.getElementById("dateoption1");
var o2 = document.getElementById("dateoption2");
var eSettings = document.getElementById("datesettings");
if(o1.checked) {
eSettings.appendChild(...);
}
else if(o2.checked) {
eSettings.appendChild(...);
}
}
But, you have to make sure to assign your radio buttons unique id values. You can duplicate names to group the radio buttons, but for any element, the id should be unique.
<form id="TestForm">
<!-- //Radio buttons -->
<input type="radio" id="dateoption1" name="dateoption" value="1">Text 1</input>
<input type="radio" id="dateoption2" name="dateoption" value="2">Text 2</text>
<!-- //Add new form elements -->
<span id="datesettings"></span>
</form>
I have a radio button named "Choose" with the options yes and no. If I select any one of the options and click the button labeled "clear", I need to clear the selected option, using javascript. How can I accomplish that?
You don't need to have unique id for the elements, you can access them by their name attribute:
If you're using name="Choose", then:
With recent jQuery
$('input[name=Choose]').prop('checked',false);
With old jQuery (<1.6)
$('input[name=Choose]').attr('checked',false);
or in pure JavaScript
var ele = document.getElementsByName("Choose");
for(var i=0;i<ele.length;i++)
ele[i].checked = false;
Demo for JavaScript
If you do not intend to use jQuery, you can use simple javascript like this
document.querySelector('input[name="Choose"]:checked').checked = false;
Only benefit with this is you don't have to use loops for two radio buttons
This should work. Make sure each button has a unique ID. (Replace Choose_Yes and Choose_No with the IDs of your two radio buttons)
document.getElementById("Choose_Yes").checked = false;
document.getElementById("Choose_No").checked = false;
An example of how the radio buttons should be named:
<input type="radio" name="Choose" id="Choose_Yes" value="1" /> Yes
<input type="radio" name="Choose" id="Choose_No" value="2" /> No
An ES6 approach to clearing a group of radio buttons:
Array.from( document.querySelectorAll('input[name="group-name"]:checked'), input => input.checked = false );
Wouldn't a better alternative be to just add a third button ("neither") that will give the same result as none selected?
In my case this got the job done:
const chbx = document.getElementsByName("input_name");
for(let i=0; i < chbx.length; i++) {
chbx[i].checked = false;
}
Simple, no jQuery required:
clear
<script type="text/javascript">
function clearChecks(radioName) {
var radio = document.form1[radioName]
for(x=0;x<radio.length;x++) {
document.form1[radioName][x].checked = false
}
}
</script>
YES<input type="radio" name="group1" id="sal" value="YES" >
NO<input type="radio" name="group1" id="sal1" value="NO" >
<input type="button" onclick="document.getElementById('sal').checked=false;document.getElementById('sal1').checked=false">
if the id of the radio buttons are 'male' and 'female', value reset can be done by using jquery
$('input[id=male]').attr('checked',false);
$('input[id=female]').attr('checked',false);
Somtimes i have to remove attribute checked from inputs type="radio" :
let el = document.getElementById('your_input_id');
el.checked = false;
el.removeAttribute('checked');
<form>
<input type="radio" name="btn"> Item1
<input type="radio" name="btn"> Item2<br>
<input type="reset">
</form>
This could work..