Radio buttons and display none - javascript

I'm creating an order form that when a button is clicked it displays an image in a separate div. The code works successfully for check boxes but with radio buttons doesn't hide the previously clicked image.
function displayImage(id) {
var el = document.getElementById(id);
if (el.style.display == "inline") {
el.style.display = "none";
} else {
el.style.display = "inline";
}
}
<tr>
<td>
<input type="radio" name="cheese" id="chkcheese" value="Yellow American" onclick="displayImage('imgamerican');" />
<label for="chkcheese">Yellow American</label>
</td>
<td>
<input type="radio" name="cheese" value="Pepper Jack" id="pepperjack" onclick="displayImage('imgjack');" />
<label for="chkjack">Pepper Jack</label>
</td>
<td>
<input type="radio" name="cheese" value="Mozzarella" id="chkmozz" onclick="displayImage('imgmozz');"/>
<label for="chkmozz">Mozzarella</label>
</td>
</tr>
<div class="cheese">
<img id="imgamerican" src="images/american-cheese-slice.png" style="display:none"/>
<img id="imgcheddar" src="images/agedcheddar.png" style="display:none"/>
<img id="imgjack" src="images/pepperJack.png" style="display:none" />
<img id="imgswiss" src="images/swisscheese.png" style="display:none" />

The click event only happens on the radio that was clicked.
You'll need to iterate the radio buttons and make sure that the deselected ones have their corresponding image hidden, or just iterate the images and hide them before showing the one that had its radio clicked.
function displayImage(id) {
var imgs = document.querySelectorAll(".cheese > img");
for (var i = 0; i < imgs.length; i++) {
imgs[i].style.display = "none";
}
document.getElementById(id).style.display = "inline";
}

It looks like your problem is that you're expecting the click event to fire when a radio button becomes unchecked. But it doesn't. You'll need to specifically change the display of the last-shown cheese, but only when it's a radio button that was clicked.
This solution is kind of a hack, but it should work in this situation:
JavaScript:
var lastUnique;
function displayImage(id, unique) {
var el = document.getElementById(id);
if (unique) {
if (lastUnique) {
lastUnique.style.display = 'none';
}
lastUnique = el;
}
el.style.display = 'block';
}
Radio buttons (note the added true):
<tr>
<td><input type="radio" name="cheese" id="chkcheese" value="Yellow American" onclick="displayImage('imgamerican', true);" />
<label for="chkcheese">Yellow American</label></td>
<td><input type="radio" name="cheese" value="Pepper Jack" id="pepperjack" onclick="displayImage('imgjack', true);" />
<label for="chkjack">Pepper Jack</label></td>
<td><input type="radio" name="cheese" value="Mozzarella" id="chkmozz" onclick="displayImage('imgmozz', true);" />
<label for="chkmozz">Mozzarella</label></td>
</tr>
So, the JavaScript keeps track of the last element shown with the unique argument being truthy, and hides it when another call with unique == true happens.
Aside:
You might look into how event handling is done in the modern world. This is the old way of doing it, and it's not exactly manageable.
Also, consider looking into modularization and encapsulation techniques.

Related

How to hide and unhide form fields based on a radio button?

I'm trying to implement a radio button, which if clicked should get more options for the user to fill in.
Here's what I've tried.
<script>
function addmentor() {
if ( document.getElementById("type_Computer").checked ) {
document.getElementById('nextSetOfComputerOptions').style.display = "";
} else {
document.getElementById('nextSetOfComputerOptions').style.display = "none";
}
}
</script>
<input type="radio" name="type" id="type_computer" value="Computer" onClick="addmentor()">Add Mentor</button>
<div id="nextSetOfComputerOptions" style="display:none;">
.
.
</div>
The above code doesn't work. When I am clicking the radio button, nothing happens, the part of the form is always hidden.
EDIT: I originally misunderstood the question and have now adjusted my answer.
Additionally, I have also included a function that will hide your input if another radio button is clicked.
See the snippet below:
//your checkbox
var checkbox = document.getElementById("type_computer");
//your div
var inputDiv = document.getElementById("nextSetOfComputerOptions");
//function that will show hidden inputs when clicked
function addmentor() {
if (checkbox.checked = true) {
inputDiv.style.display = "block";
}
}
//function that will hide the inputs when another checkbox is clicked
function hideInputDiv() {
inputDiv.style.display = "none";
}
<input type="radio" name="type" id="type_computer" value="Computer" onChange="addmentor();" ">Add Mentor</input>
<input type="radio" name="type" onClick="hideInputDiv();">Other radio input</input>
<div id="nextSetOfComputerOptions" style="display: none;">
<input placeholder="PC"></input>
<input placeholder="Mac"></input>
</div>

2 Arrays Working as 1

I have two separate radio button arrays that should behave as if they are one. Currently, I have it only working one way. I have a YouTube video showing my problem.
I have two mutually exclusive arrays that I want them working together as one array to the user. E.g., If one radio button is checked" in one array, I do not want the other array's radio button checked, but unchecked. JavaScript should deselect the radio button in the other array, making the functionality to look like the user is working with one set of radio buttons. The two separate radio arrays have different name=pair values.
YouTube Video Showing Problem
https://www.youtube.com/watch?v=nlvzgu3pJ8A
<!DOCTYPE html>
<html lang="en-US">
<head>
<style>
body{font-family:sans-serif, arial;}
th{text-align:left;}
h3,h4{margin-top:.15em; padding:0;}
</style>
<script>
function monthlyPlan(){
for(var i=0; i<document.deliveryForm.monthly.length;++i)
{
if(document.deliveryForm.monthly[i].checked== true )
document.deliveryForm.weekly.checked = false;
}
}
function weeklyPlan(){
for(var i=0; i<document.deliveryForm.weekly.length;++i)
{
if(document.deliveryForm.weekly[i].checked == true)
document.deliveryForm.monthly.checked = false;
}
}
</script>
</head>
<body>
<form name="deliveryForm" action="FormProcessor.html" method="get">
<h3>Delivery Rates</h3>
<h4>Allow users to select their desired delivery option.</h4>
<ul>
<li>Bill weekly or monthly</li>
<li>Devlivered Mon-Sat or Everyday</li>
</ul>
<p>
<strong>Billed continuously $3.50 by the Month?</strong>
<input type="radio" name="monthly" value="yes" onclick="monthlyPlan();" /> Yes
</p>
<strong>Billed by a Weekly Plan?</strong>
<table border=1 cellpadding=6>
<tr>
<th></th>
<th>4 weeks</th>
<th>13 weeks</th>
<th>26 weeks</th>
<th>52 weeks</th>
</tr>
<tr>
<th>Devlivered Mon-Sat</th>
<td><input type="radio" name="weekly" value="12.60" onclick="weeklyPlan();" />12.60</td>
<td><input type="radio" name="weekly" value="40.95" onclick="weeklyPlan();" />40.95</td>
<td><input type="radio" name="weekly" value="81.90" onclick="weeklyPlan();" />81.90</td>
<td><input type="radio" name="weekly" value="156.00" onclick="weeklyPlan();" />156.00</td>
</tr>
<th>Devlivered Everyday</th>
<td><input type="radio" name="weekly" value="13.56" onclick="weeklyPlan();" />13.56</td>
<td><input type="radio" name="weekly" value="44.07" onclick="weeklyPlan();" />44.07</td>
<td><input type="radio" name="weekly" value="88.14" onclick="weeklyPlan();" />88.14</td>
<td><input type="radio" name="weekly" value="159.74" onclick="weeklyPlan();" />159.74</td>
</tr>
</table>
</form>
</body>
</html>
Try this:
function monthlyPlan() {
for (var i = 0; i < document.deliveryForm.weekly.length; ++i) {
document.deliveryForm.weekly[i].checked = false;
}
}
function weeklyPlan() {
document.deliveryForm.monthly.checked = false;
}
Demo: http://jsfiddle.net/DpbMB/
You don't need to test whether the radio that was just clicked is checked, because for radio buttons you know they will be checked when the click event occurs (there's no way to uncheck them by clicking except by clicking on another in the group, and then it is the other that gets the event).
When the monthly radio button is clicked, loop over all of the weekly radio buttons and set them to not be checked. When any weekly radio is clicked simply uncheck the monthly one.
The array-style access is only applicable when there is more than one element with the same name, so to access the monthly button don't use [i].
It seems to me though that it would be easier to just make the monthly button part of the same group, and give it an appropriate value that you can test server-side.
Try the following for your monthlyPlan() function:
function monthlyPlan(){
/*for(var i=0; i<document.deliveryForm.monthly.length;++i)
{
if(document.deliveryForm.monthly.checked== true )
document.deliveryForm.weekly.checked = false;
}
*/
alert(document.deliveryForm.monthly.length); // will say undefined
if (document.deliveryForm.monthly.checked)
{
for (var k = 0; k < document.deliveryForm.weekly.length; ++k)
{
document.deliveryForm.weekly[k].checked = false;
}
}
}
It appears that when you only have one radio button in the group, the DOM doesn't treat it as an array.
EDIT: Actually, nnnnnn's answer is better. No point keeping the redundant if statements.

I want to show tables when radio buttons are selected

I am trying to show tables onClick or onSelect of a couple of checkboxes. I have a checkbox for 'standard' which, when selected, should display a table of standard options, and I have a checkbox for 'customized' which, when selected, should display a table of customized options.
Right now the tables toggle but won't show at the same time. In other words, if both are checked, I need both tables to display, one under the other. If only 'standard' is checked, then only 'standard' options show, and if only 'customized' is checked, then only 'customized' options show.
Here is a fiddle: http://jsfiddle.net/4tcRD/2/
Here is my JS:
function toggleTables(which)
{
if(which == "1") {
document.getElementById('customize').style.display = "table";
document.getElementById('standard').style.display = "none";
}
if(which == "2") {
document.getElementById('standard').style.display = "table";
document.getElementById('customize').style.display = "none";
}
}
Here is my HTML:
<input name="checkbox1" type="checkbox" id="customize_1" onClick="toggleTables('2')" value="checkbox" />
<label for="checkbox1"></label> Standard
<input name="checkbox2" type="checkbox" id="customize_0" onClick="toggleTables('1')" value="checkbox" checked="checked" />
Customize
<br />
<table width="100%" class="imagetable" cellpadding="0" cellspacing="0" id="customize">
<tr><td>customize</td></tr>
</table>
<table width="100%" class="imagetable" cellpadding="0" cellspacing="0" id="standard" style="display: none">
<tr><td>standard</td></tr>
</table>
Please give me a hand. - UPDATED WITH CHECKBOXES**
Can just check the status of checkbox within function.
function toggleTables()
{
var isCustomize = document.getElementById('customize_1').checked;
var isStandard = document.getElementById('standard_1').checked;
var customize = document.getElementById('customize');
var standard = document.getElementById('standard');
customize.style.display = isCustomize ? 'table' : 'none';
standard.style.display = isStandard ? 'table' : 'none';
}​
http://jsfiddle.net/4tcRD/3/

onclick() action is not responding

I'm creating a survey-like page. I use three basic JavaScript functions, goNext(i) which hides a certain div tags and shows the next, goPrevious(i), which pretty much does the same but backwards, and answerExists(questionNumber) which checks if all radio buttons are checked. From the point I created answerExists(), goNext() and I suppose goPrevious() too, stopped responding. Maybe it's something to do with the onsubmit() function, but I can't figure it out. These are the JavaScript functions:
function goNext(i) {
document.getElementById("div" + i).style.display = 'none';
document.getElementById("div" + (i + 1)).style.display = 'block';
}
function goPrevious(i) {
document.getElementById("div" + i).style.display = 'none';
document.getElementById("div" + (i - 1)).style.display = 'block';
}
function checkAnswers(questions) {
var answers = new Array(questions);
for(var i = 1; i <= questions; i++){
answers[i-1] = false;
var radio = document.getElementsByClassName('Radio' + i);
for (var j=0; j < radio.length; j++) {
if(radio[j].checked == true)
alert(radio[j].value)answers[i-1] = true;
}
for (var i = 0; i < questions; i++){
if(answers[i] == false){
alert("Please answer all questions.");
return false;
}
}
return true;
}
And this is the HTML form:
<form id="content" action="getresults.jsp" method="post" onsubmit="return checkAnswers(2);">
<div id="div1" style="display: block;">
<strong>1. Question 1</strong><br><br>
<input id="radio1" class="radio1" name="radio1" onclick="if (this.__chk) this.checked = false" onmousedown="this.__chk = this.checked" type="radio" value="Answer1" />
Answer1<br><br><br><br>
<div class="auto-style1">
<input name="next" onclick="goNext(1);" type="button" value="Next" />
</div>
</div>
<div id="div2" style="display: none;">
<strong>2. Question 2</strong><br><br>
<input id="radio2" class="radio2" name="radio2" onclick="if (this.__chk) this.checked = false" onmousedown="this.__chk = this.checked" type="radio" value="Answer 2" />
Answer 2<br><br>
<input id="radio2" class="radio2" name="radio2" onclick="if (this.__chk) this.checked = false" onmousedown="this.__chk = this.checked" type="radio" value="dfgdgfdgf" />
dgfgddgf<br><br><br><br>
<div class="auto-style1">
<input name="previous" onclick="goPrevious(2);" type="button" value="Previous" />
<input name="submit" type="submit" value="Submit" />
</div>
</div>
</form>
It is actually all created dynamically, but still, it worked before I added the checkAnswers() function.
The problem is that you have syntax errors in your checkAnswers function, and the interpreter discards any scripts that contain syntax errors, so all your other functions get discarded, too.
These are the two syntax errors:
alert(radio[j].value)answers[i-1] = true; is not a valid statement. (I'm guessing that you intended to delete the alert(radio[j].value) part, but highlighted the wrong thing?)
You have more left-curly-braces { than right-curly-braces }.
Once you fix both of these issues, the script should at least run (though you may still have some debugging to do).
You are calling checkAnswers with a 2 as parameter and build an array with it. ????
The code below will show the mistake.
try{
//your code
}catch(er){
alert(er);
}
I like to answer you step by step....
1) Why do you really need to check whether answers for all questions are checked?
I asked you this because radio buttons will have selected an option by default... or you can make an "active" thing for a particular option... By doing this you really don't need to check whether all questions are answered... since by default one answer is selected...
2) The click event doesnt work because it seems you don't have any "id" for input tags "next","previous","submit"... Have separate id's for each and capture the click event of that particular tag by using jquery...
eg. Have an id for next <input id="next">
$("#next").click(function() {
//perform the action you need
}
Do this for all click events....
3) Finally... don't use input tags for elements you like to click... Try using button tags...
Hope it ll help you :)...

How to display diffrence divs according to radio selection

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>

Categories

Resources