How to display different content when a user selects a radio button? - javascript

I want make one feature. HTML/PHP is no problem, but my JavaScript skill is really low. I know how to use it, but I don't know how to write such a thing. It should look like this example.
Under the picture, there's something called a "MILESTONE" - but in this case, the action is onhover. I want to use the onclick event and a set of radio buttons. When the user clicks on one of the three radio buttons, the page will change the picture and the description, depending on which one was clicked - and without refreshing the page.
I don't really get how it works, but if each option were one single page and I could just include them all, it would be ideal.

Your question is fairly broad, so I'm going to focus on the task of swapping visible content on a fired event.
Writing this in jQuery, but you should be able to translate it if you're not using JQ:
HTML:
<input type="radio" name="picker" class="picker" value="1"/>
<input type="radio" name="picker" class="picker" value="2"/>
<input type="radio" name="picker" class="picker" value="3"/>
<ul class="content">
<li><img src="foo1"/></li>
<li><img src="foo2"/></li>
<li><img src="foo3"/></li>
</ul>
CSS:
.content li { display: none; }
.content li.active { display: block; }
JavaScript:
$('.picker').on('click', function() {
$('.content .active').removeClass('active');
$('.content li').eq($(this).val() - 1).addClass('active');
});
Working example: http://jsfiddle.net/9SdvZ/1/

If your skills are good enough in HTML & CSS then you will know how to style it properly. Here is a sample code I have just done that has the JavaScript (functionality).
Live example: http://embed.plnkr.co/xdpHX9FplgLgh9pN7lWZ/preview
Explanation:
You will have the following HTML markup:
<div id="controls">
<input type="radio" name="slide" value="slide1.html"> 1
<input type="radio" name="slide" value="slide2.html"> 2
<input type="radio" name="slide" value="slide3.html"> 3
</div>
And you will have the following JavaScrit using jQuery:
$(function(){
$('#controls').on('click', ':radio', function(e) {
var target = $(e.target);
$.get(target.val(), function(data) {
$('#content').html(data);
});
});
});
Basically, the JavaScript (using jQuery) will do the following: after clicking a radio button the <div id="controls" />'s content will be replaced with the content of the file specified in the radio button value attribute.

Related

Show one div and hide the other by checked radio button

I'm trying to learn how to use jquery to show/hide elements dependent on values. i'm not sure if .show / .hide is the right choice so any help will be appreciated...
Here is my example on jsfiddle where I have 2 radio buttons and 2 divs.
I want Jquery to show a single div by the dependency of the checked radio button, so it will show only the one that is checked.
HTML:
<input type="radio" name="one" value="01" checked> Male<br>
<input type="radio" name="two" value="02"> Female<br>
<div class="showhide">
show me when 01 is checked.
</div>
<div class="showhide">
show me when 02 is checked.
</div>
JQuery (trying to understand what to do here):
$("div.showhide").hide();
$("div.showhide").show();
// or maybe with:
$("div.showthis").toggle(this.checked);
Using data-* attributes comes in handy in such practices. Rember that the radios name attributes must be the same that one and only one checkbox can be checked at any given time. And, there is no p tag in your code, at least in the example provided, so why bother prefixing the selector with it?
The following example makes use of data-section attribute which has the selector for the element that must be shown when the checkbox is checked. It is worth mentioning that this is code is dynamic and does not require changing the code when adding more inputs with divs.
$(function() {
// listen for changes
$('input[type="radio"]').on('change', function(){
// get checked one
var $target = $('input[type="radio"]:checked');
// hide all divs with .showhide class
$(".showhide").hide();
// show div that corresponds to selected radio.
$( $target.attr('data-section') ).show();
// trigger the change on page load
}).trigger('change');
});
.showhide {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="radio" name="one" data-section="#div-1" value="01" checked>Male<br>
<input type="radio" name="one" data-section="#div-2" value="02">Female<br>
<div id="div-1" class="showhide">
show me when 01 is checked.
</div>
<div id="div-2" class="showhide">
show me when 02 is checked.
</div>

Make a checkbox look like a button CSS

I think what I am trying to achieve can be done in a simpler manner. However I have little JS experience and none in the way of CSS. So I’m utilizing prebuilt CSS and JS code and subtlety modifying it. So I will explain my end goal and see if what I currently have is acceptable.
A top menu on the webpage that has push buttons and checkboxes that all visually look the same
I would like checkboxes to look like buttons, e.g. no checkbox only the label.
I would like for the checkbox to still retain its functionality as a checkbox given the JS code it is calling
Is the way I’m calling the JS code through the button and checkbox correct or too complicated?
JSFiddle
<li><a title="Zoom to U.S" input type="button" name="US" onclick="US();"><span>Zoom to U.S.</span></a></li>
<li><a title="Test 1 KML"><input type="checkbox" id="kml-red-check" name="kml-red-check" onclick="toggleKml("red");"><span>Test 1 KML</span></a></li>
.hidden {
position: absolute;
visibility: hidden;
opacity: 0;
}
input[type=checkbox]+label {
color: #ccc;
font-style: italic;
}
input[type=checkbox]:checked+label {
color: #f00;
font-style: normal;
}
<input type="checkbox" class="hidden" name="cb" id="cb">
<label for="cb">text</label>
http://css-tricks.com/almanac/selectors/c/checked/
Won't work on lt IE9 though.
edit: Following your markup it should be something like this:
<ul>
<li><input id="cb1" name="cb1-name" type="checkbox" onkeypress="setTimeout('checkIt(\'cb1\')',100);"><label for="cb1" onclick="setTimeout('checkIt(\'cb1\')',100);">text 1</label></li>
<li><input id="cb2" name="cb2-name" type="checkbox" onkeypress="setTimeout('checkIt(\'cb2\')',100);"><label for="cb2" onclick="setTimeout('checkIt(\'cb2\')',100);">text 2</label></li>
</ul>
And then check if the checkbox is checked or not in your function.
onchange / onclick in a checkbox doesn't work in IE
edited again: changed NAME attribute so you won't end up having problems further along the line. And added a little workaround for the unresponsive, though ultimately desired, onchange functionality in IE8. Eventually you should add a timer to your function, rather than inline.
function checkIt(e){
if(document.getElementById(e).checked){
alert('checked');
} else {
alert('unchecked');
}
}
It is not possible to change the appearence of a checkbox so radically using CSS.
What you CAN do though, is style a label element enough to make it look like a button. Due to the nature of the label element, clicking it will toggle the state of the checkbox keeping your functionality intact.
Here is how to do it
Markup
<li>
<label for="kml-red-check">I am a button!</label>
<input type="checkbox" id="kml-red-check" name="kml-red-check" onchange="toggleKml("red");">
</li>
Note that I've changed the onclick handler to onchange since now it is impossible to click the checkbox itself. Its value changes though when you click on the label
Styling
label[for="kml-red-check"]{
//Your CSS goes that makes the label look like a button goes here
}
#kml-red-check{
display:none;
}
<label>
<input type="checkbox" ng-model="vm.abc" ng-change="vm.go()"/>
<span>this is button add some css to lokking like a button</span>
</label>
this will work like button , if you don't want to show checkbox use this
<label>
<input type="checkbox" ng-model="vm.abc" ng-change=vm.go()" hidden=''/>
<span>this is button add some css to lokking like a button</span>
</label>
check it out here https://jsfiddle.net/h0ntpwqk/2/

DOM (Javascript) show / hide divs not working [duplicate]

This question already exists:
Javascript Child Window Stay on Top
Closed 9 years ago.
I am unable to use AJAX (Server issues!) so am having to rely on DOM + javascript to show or hide two of the divs on my page.
A user clicks one of two radio buttons and depending on which is click the appropriate div is displayed.
For some reason the first div will load if the "EU" radio button is used but I cannot get the "international" radio button to work. The second button calls the correct script, passes the variable and even hides the EU div, it just will not display the international one.
I'm at my wits end. Can anybody help?
Javascript:
function displayLocation(loc){
alert(loc)
document.getElementById(loc).style.display = "block"
if (loc == "eu"){
document.getElementById("international").style.display = "none"
}else{
document.getElementById("eu").style.display = "none"
}
}
HTML Radio buttons
<input type="radio" name="loc" style="float:left;" onclick=displayLocation("eu")>
<input type="radio" name="loc" style="float:left;" onclick=displayLocation("international")>
Divs to hide/display as appropriate
<div id="eu" style="display:none;">European Union</div>
<div id="international" style="display:none;">International</div>
Take a look at the fiddle I just made.
I was able to resolve the problem by placing the script after the HTML that calls it. There's a couple of stylistic things to tweak too (onclick=displayLocation should be in quotes) but other than that it should work fine for you.
You need to wrap quotes around displayLocation('xx') in the onlick attribute as in: 'displayLocation("eu")'
http://jsfiddle.net/rvtBp/
I would also suggest using event bindings instead of event attributes:
<input type="radio" name="loc" style="float:left;" data-lang="eu">
<input type="radio" name="loc" style="float:left;" data-lang="international">
Array.prototype.forEach.call(document.querySelectorAll('[name="loc"]'),
function (elem) {
elem.addEventListener('change', function (e) {
if (this.checked) {
displayLocation(this.dataset.lang);
}
});
});
http://jsfiddle.net/rvtBp/1/
<input type="radio" name="loc" style="float:left;" onclick="displayLocation(\'' + eu + '\')">
onclick declaration should enclosed in quotes..onclick="displayLocation(\'' + eu + '\')"
i think it wont works.. document.getElementById(loc).style.display = "block"
document.getElementById("+loc+").style.display = "block"
you have to change onclick event to look like this
<input type="radio" name="loc" style="float:left;" onclick="displayLocation('eu')">
<input type="radio" name="loc" style="float:left;" onclick="displayLocation('international')">

Refreshing input:radio from iframe using Jquery Mobile

I'm trying to change the selected option of an input:radio (that is in the main page) dynamically clicking a button inside an iframe.
To do this, y pass by parameter the variable containing the input:radio element:
//code from iframe.js
button.live("click", function(e) {
var inputRadioContainer = $(window.parent.document).find('#inputRadioContainer');
changeInputRadio(inputRadioContainer, "email");
});
//code from mainPage.js
function changeInputRadio(inputRadioContainer, val){
inputRadioContainer.find('input:radio[value=val]').attr('checked',true).checkboxradio('refresh');
}
//HTML content of inputRadioContainer
<ul id="inputRadioContainer" data-role="listview">
<li>
<fieldset data-role="controlgroup" data-type="horizontal" data-role="fieldcontain" data-mini="true">
<input type="radio" name="radio-contacto" id="radio-contacto-1" value="email"/>
<label for="radio-contacto-1" value="email">email</label>
<input type="radio" name="radio-contacto" id="radio-contacto-2" value="tlf"/>
<label for="radio-contacto-2" value="tlf">telf</label>
</fieldset>
</li>
</ul>
After executing that code, the "checked" attribute of the required radio is setted to "checked" (as expected), but the radio is not displayed checked. It seems that ".checkboxradio('refresh');" is not working. I also tried doing "inputRadioContainer.listview('refresh')" but it doesn't work.
Anyone knows how to solve the problem?
Thank you very much!!
Solution:
Using
inputRadioContainer.find('input:radio[value=val]').attr('checked',true).trigger('click');
instead of
inputRadioContainer.find('input:radio[value=val]').attr('checked',true).checkboxradio('refresh');
I hope helping someone

jQuery/JavaScript - Hide / Show Drop down box pending on Radio Button

I want to make it so that the drop-down is only displayed when the radio button (option 3) is clicked and have it hidden if either 1 or 2 is selected. What would be the best way to complete this? I have a little bit of experience with JavaScript and slim to none with jQuery but it seemed like it might be the way to go.
Thanks for any help,
Dan
Here is the HTML code I have as of now:
<p class="help">Selection:</p>
<div id='buttons'>
<label><input type="radio" name="select" /> Option 1 </label>
<label><input type="radio" name="select" /> Option 2</label>
<label><input type="radio" name="select" /> Option 3</label>
</div>
<div id="list" style="display: none;">
<label>Please Select From the List:
<select>
<option>True</option>
<option>False</option>
</select>
</label>
</div>
$(document).ready(function(){
$("[name=select]").change(function(){ // Whenever the radio buttons change
$("#list").toggle($("[name=select]").index(this)===2); // Only keep the list open when it's the last option (First option = 0, Third option = 2)
});
});
This code in action.
Assuming you are using jquery, as it sounds like it from your question, you could modify your HTML like so:
<p class="help">Selection:</p>
<div id='buttons'>
<label><input type="radio" name="select" id="option1" /> Option 1 </label>
<label><input type="radio" name="select" id="option2" /> Option 2</label>
<label><input type="radio" name="select" id="option3" /> Option 3</label>
</div>
<div id="list">
<label>Please Select From the List:
<select id="mySelect">
<option>True</option>
<option>False</option>
</select>
</label>
</div>​
</p>
Then you could write some jquery like so:
$(document).ready(
function()
{
$("#option1, #option2, #option3").click(
function()
{
if (this.id == "option3")
$("#mySelect").hide();
else
$("#mySelect").show();
});
});​
You can see it working here: http://jsfiddle.net/AVFuY/3/
EDIT: I removed the unneeded class and just used the id's so as to not confuse and add unnecessary code.
Since this is a fairly basic question, I think it'll be instructional to walk you through the jQuery documentation while I answer your question. If you know truly nothing about jQuery, I recommend following this short tutorial first -- it will make things much, much easier for you in the future: jQuery Documentation - Getting Started With jQuery
Your requirement is that something happens (in this case, another element is hidden/shown) when we click the radio buttons. There's two parts to this problem: first, we need to find the radio buttons, then we need to make something happen when we click it.
1. Finding the radio buttons
Take a look at the jQuery Selector documentation here: http://api.jquery.com/category/selectors/
As you can see, there's a specific pseudo-selector for radio buttons, ":radio". We want to select everything inside of the element with ID "buttons", so this is how the selector will look in total:
$("#buttons input:radio");
By the way, it's called a "pseudo-selector" because it filters items we've already selected (in this case, input tags inside of a div with id "button"). Pseudo-selectors always start with a ":".
2. Making something happen when we click them
Consult the jQuery Events reference here: http://api.jquery.com/category/events/
We want the ".click()" event here, clearly. Once we've selected our elements, we can apply a click handler to them like this:
$("#buttons input:radio").click(function() {
// make something happen here
alert("input button clicked: " + $(this).index());
});
Note that this will apply the same click handler to all three of the input buttons, but you can access the specific element that was clicked via the "this" keyword. Wrapping $() around it makes it into a jQuery selection rather than just a Javascript object and allows us to call jQuery functions on it.
3. Hiding and showing the list element conditionally
Let's extend the code above to actually hide and show that other div, depending on which item was clicked. We're going to refer to the jQuery Effects documentation so that we can make hiding and showing it exciting: http://api.jquery.com/category/effects/
The functions we'll be using are ".slideUp()", which hides an element, and ".slideDown()", which shows it. We'll also be using the ".index()" function I used in the previous example to figure out which button was clicked, although I recommend giving the button a unique ID in the future so that your code isn't dependent on the order of the buttons. Here's the final code:
$("#buttons input:radio").click(function() {
// if it was the third button (0-indexed, so the 3rd one is index 2)...
if ($(this).index() == 2) {
// display the element with ID "list"
$("#list").slideDown();
}
else {
// hide the element with ID "list"
$("#list").slideUp();
}
});
Sorry for the length of this answer, but hopefully it was more conducive to your understanding of jQuery than "copy and paste this 3-line super-compact solution".
<label><input type="radio" name="select" onclick="document.getElementById('list').style.display=this.checked?'':'none'" /> Option 3</label>
Without changing your markup:
$(function()
{
$("#list").hide();
$("#buttons input:radio[name=select]").click(function()
{
var myindex = $("#buttons input:radio[name=select]").index(this);
if (myindex == 2)
{
$("#list").show();
}
else
{
$("#list").hide();
};
});
});
EDIT: Another option: just show it on the last button in the list.
$(function()
{
$("#list").hide();
$("#buttons input:radio[name=select]").click(function()
{
var myindex = $("#buttons input:radio[name=select]").index(this);
var lastone = $("#buttons input:radio[name=select]:last").index("#buttons input:radio[name=select]");
if (myindex == lastone)
{
$("#list").show();
}
else
{
$("#list").hide();
};
});
});

Categories