Change content of div based on radio button selection - javascript

I've been trying for a long time to make a button appear on a webpage and make the link that button goes to change depending on the radio button selected. However, so far nothing appears on my web page except for the radio buttons.
This is my code so far:
<div id="quick-book">
<script>
if (document.getElementById("radio-restaurant").checked){
document.getElementById("button").innerHTML = "<a href='./restaurant.html'>Submit</a>";
} else if (document.getElementById("radio-hotel").checked){
document.getElementById("button").innerHTML = "<a href='./hotel.html'>Submit</a>"
}
</script>
<form name="frmRadio" id="radio-buttons" action="">
<input type="radio" id="radio-restaurant" name="option" onclick="document.getElementById('radio-buttons').action='';">Restaurant<br>
<input type="radio" id="radio-hotel" name="option" onclick="document.getElementById('radio-buttons').action='';">Hotel<br>
</form>
<div name ="button">
</div>
</div>
I hope someone here can help guide me in the right direction!

You should add a function in you code and add it when click in the radio.
Something like this:
<script>
function myFunction() {
if (document.getElementById("radio-restaurant").checked){
document.getElementById("button").innerHTML = "<a href='./restaurant.html'>Submit</a>";
} else if (document.getElementById("radio-hotel").checked){
document.getElementById("button").innerHTML = "<a href='./hotel.html'>Submit</a>"
}
}
</script>
<div id="quick-book">
<form onchange="myFunction()" name="frmRadio" id="radio-buttons" action="">
<input type="radio" id="radio-restaurant" name="option" onclick="document.getElementById('radio-buttons').action='';">Restaurant<br>
<input type="radio" id="radio-hotel" name="option" onclick="document.getElementById('radio-buttons').action='';">Hotel<br>
</form>
<div id="button">
</div>
</div>
And change name="button" to id="button"

First, your <script> is executed only once, not on every radio button change. And since initially nothing is checked, script does nothing. Moreover, when this script is executed, elements below are not rendered yet. You need to:
1) Move the script down, below all your divs.
2) Create a change callback to check radio buttons values
<div id="quick-book">
<form name="frmRadio" id="radio-buttons" action="">
<input type="radio" id="radio-restaurant" name="option" onclick="change(this)">Restaurant<br>
<input type="radio" id="radio-hotel" name="option" onclick="change(this)">Hotel<br>
</form>
<div id ="button">
</div>
</div>
<script>
function change(radio) {
if (radio.checked && radio.id === "radio-restaurant") {
document.getElementById("button").innerHTML = "<a href='./restaurant.html'>Submit</a>";
} else {
document.getElementById("button").innerHTML = "<a href='./hotel.html'>Submit</a>"
}
}
</script>

<div id="quick-book">
<script>
function checkRadio(radio) {
if (radio.id === "radio-restaurant"){
document.getElementById("button-div").innerHTML = "<a href='./restaurant.html'>Submit</a>";
} else {
document.getElementById("button-div").innerHTML = "<a href='./hotel.html'>Submit</a>";
}
}
</script>
<form name="frmRadio" id="radio-buttons" action="">
<input type="radio" id="radio-restaurant" name="option" onchange="checkRadio(this)">Restaurant<br>
<input type="radio" id="radio-hotel" name="option" onchange="checkRadio(this)">Hotel<br>
</form>
<div id="button-div">
</div>
</div>

Try this:
<div id="quick-book">
<script>
function $(e) {
//Just something I have found useful
return document.getElementById(e);
}
function rb_onchange(s) {
//First clean up
$("button").innerHTML = '';
//The id is added because both radio buttons
//will fire this event when one changes
//So to prevent both both conditions firing you have to add this additional condition
if (s.checked && s.id == "radio-restaurant") {
//If the radio button is checked and the id of
//said radio button is the restaurant one then add the innerHTML
$("button").innerHTML = "<a href='./restaurant.html'>Submit</a>";
}
else if (s.checked && s.id == "radio-hotel") {
//If the radio button is checked and the id of
//said radio button is the hotel one then add the innerHTML
$("button").innerHTML = "<a href='./hotel.html'>Submit</a>";
}
}
</script>
<form name="frmRadio" id="radio-buttons" action="">
<input type="radio" id="radio-restaurant" name="option" onchange="rb_onchange(this);">Restaurant<br>
<input type="radio" id="radio-hotel" name="option" onchange="rb_onchange(this);">Hotel<br>
</form>
<div name ="button"></div>
</div>
EDIT:
Seems I failed to notice the id attribute of the button div.,....
Change:
<div name ="button"></div>
to
<div name="button" id="button"></div>
EDIT:
Adding some comments

$(document).ready(function ()
{
$("#watch-me").click(function()
{
$("#show-me:hidden").show('slow');
$("#show-me-two").hide();
$("#show-me-three").hide();
});
$("#watch-me").click(function()
{
if($('watch-me').prop('checked')===false)
{
$('#show-me').hide();
}
});
$("#see-me").click(function()
{
$("#show-me-two:hidden").show('slow');
$("#show-me").hide();
$("#show-me-three").hide();
});
$("#see-me").click(function()
{
if($('see-me-two').prop('checked')===false)
{
$('#show-me-two').hide();
}
});
$("#look-me").click(function()
{
$("#show-me-three:hidden").show('slow');
$("#show-me").hide();
$("#show-me-two").hide();
});
$("#look-me").click(function()
{
if($('see-me-three').prop('checked')===false)
{
$('#show-me-three').hide();
}
});
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
<div class="row">
<div class="col-sm-12" align="center">
<form id='form-id'>
<input id='watch-me' name='test' type='radio' checked /> Radio 1
<input id='see-me' name='test' type='radio' /> Radio 2
<input id='look-me' name='test' type='radio' /> Radio 3
</form>
<br><br>
<div id='show-me'>
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active">Home</li>
<li role="presentation">Profile</li>
<li role="presentation">Messages</li>
<li role="presentation">Settings</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="home">Home Tab Content</div>
<div role="tabpanel" class="tab-pane" id="profile">Profile Tab Content</div>
<div role="tabpanel" class="tab-pane" id="messages">Messages tab Content</div>
<div role="tabpanel" class="tab-pane" id="settings">Setting tab Content</div>
</div>
</div>
<div id='show-me-two' style='display:none; border:2px solid #ccc'>Editing snippet "On Click Change on Radio Button" <br> Editing snippet "On Click Change on Radio Button"</div>
<div id='show-me-three' style='display:none; border:2px solid #ccc'>Hello I'm Div 3</div>
</div>
</div>

Related

How to Select Radio Button When Clicking Label & Pass Data to URL?

I would like to be able to select a radio button when clicking on "label" and then pass that value to the URL.
Here's the URL Prefill code below.
It works if you select the actual radio button. However, I realized that if you click on label it doesn't select the radio button.
So i added this top part jquery code to solve that issue. However, it doesn't pass the value to the URL.
I'd like to stylize radio buttons by hiding input part and adding pseudoclasses. so i wonder if there's a way to pass radio button value when label is clicked on?
$(function(){
$('li').click(function(){$(this).find('input[type=radio]').prop('checked', true);});
});
/* URL Prefill Code */
var form = document.getElementById('form-product-choices');
form.addEventListener('change', function(e){
var actionUrl = 'https://example.com/';
var radioButtons = document.getElementsByName('product-choice');
for( var i = 0; i < radioButtons.length; i++ ) {
if( radioButtons[i].checked ) {
actionUrl += '?product-choice=' + radioButtons[i].value;
break;
}
}
document.getElementById('action-link').href = actionUrl;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<form id='form-product-choices' action=''>
<main role="main">
<section id="p1">
<ul>
<li><label for="radio"><input type='radio' name='product-choice' value='regular' /> regular</label></li>
<li><label for="radio"><input type='radio' name='product-choice' value='double' /> double</label></li>
<li><label for="radio"><input type='radio' name='product-choice' value='max-xl' /> xl</label></li>
</ul>
<a class="quizbut">Next</a>
</section>
<section id="p4">
<a id='action-link' class='quizbut' href=''>Click to continue</a>
</section>
</main>
</form>
First of all, we don't need JQuery code for select the radio button when clicking the label. Instead of this you can able to use below code,
<label for="regular">
<input type='radio' name='product-choice' value='regular' id="regular" /> regular
</label>
For achieving this, Need to set the ID attribute in textbox and use that ID attribute value on label 'for' attribute.
Below, I have added a full code. Hope this will help.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<form id='form-product-choices' action=''>
<main role="main">
<section id="p1">
<ul>
<li>
<label for="regular">
<input type='radio' name='product-choice' value='regular' id="regular" /> regular
</label>
</li>
<li>
<label for="double">
<input type='radio' name='product-choice' value='double' id="double" /> double
</label>
</li>
<li>
<label for="xl">
<input type='radio' name='product-choice' value='max-xl' id="xl" /> xl
</label>
</li>
</ul>
<a class="quizbut">Next</a>
</section>
<section id="p4">
<a id='action-link' class='quizbut' href='javascript:void(0)'>Click to continue</a>
</section>
</main>
</form>
<script type="text/javascript">
$("#action-link").click(function(){
var getVal = $('input[name=product-choice]:checked').val();
window.location.href='https://example.com/test.cfm?product-choice='+getVal;
});
</script>
On the label, associate the for attribute with a corresponding id on each of the radio buttons. The ids should be unique between them.
$(function(){
$('li').click(function(){$(this).find('input[type=radio]').prop('checked', true);});
});
/* URL Prefill Code */
var form = document.getElementById('form-product-choices');
form.addEventListener('change', function(e){
var actionUrl = 'https://example.com/';
var radioButtons = document.getElementsByName('product-choice');
for( var i = 0; i < radioButtons.length; i++ ) {
if( radioButtons[i].checked ) {
actionUrl += '?product-choice=' + radioButtons[i].value;
break;
}
}
document.getElementById('action-link').href = actionUrl;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<form id='form-product-choices' action=''>
<main role="main">
<section id="p1">
<ul>
<li><label for="regular"><input id="regular" type='radio' name='product-choice' value='regular' /> regular</label></li>
<li><label for="double"><input id="double" type='radio' name='product-choice' value='double' /> double</label></li>
<li><label for="max"><input id="max" type='radio' name='product-choice' value='max-xl' /> xl</label></li>
</ul>
<a class="quizbut">Next</a>
</section>
<section id="p4">
<a id='action-link' class='quizbut' href=''>Click to continue</a>
</section>
</main>
</form>

CSS hide div with radiobutton outside form

I am trying to hide a div through css.
The div hide is working inside the form, how can this be done outside the form, or even outside the div row?
HTML
<div class="row">
<form>
<input type="radio" name="radio" value="show" checked/>Show <br>
<input type="radio" name="radio" value="hide"/>Hide
<div class="hideDiv">
<p>Can you see me</p>
</div>
</form>
</div>
CSS
input[type=radio][value="hide"]:checked ~ .hideDiv {
display: none;
}
Preferably only css but javascript is also a option.
Use less CSS specificity.
.hideDiv {
display: none;
}
maybe something similar to this code will help?
<input type="radio" name="radio" onclick="hideFunc();" value="show" checked/>Show <br>
<input type="radio" name="radio" onclick="hideFunc();" value="hide"/>Hide
<script>
hideFunc = function() {
if (document.getElementsByClassName('hideDiv')[0].style.display == "none")
document.getElementsByClassName('hideDiv')[0].style.display = "block";
else
document.getElementsByClassName('hideDiv')[0].style.display = "none";
}
</script>
You could try this:
favorite
I am trying to hide a div through css. The div hide is working inside the form, how can this be done outside the form, or even outside the div row?
HTML
<div class="row">
<form>
<input type="radio" name="radio" value="show" onclick="hideDiv();" checked/>Show <br>
<input type="radio" name="radio" onclick="hideDiv();" value="hide"/>Hide
<div class="hideDiv">
<p>Can you see me</p>
</div>
</form>
</div>
JS
function hideDiv() {
var aux = $('input[name="radio"]:checked').val();
if (aux == 'show'){
$('.hideDiv').css("display","block");
}else{
$('.hideDiv').css("display","none");
}
}
you can do it easily using jquery
$('.chkToogle').click(function(){
$('.hideDiv').fadeToggle();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<form>
<input type="checkbox" class="chkToogle" checked/>Show/Hide
</form>
</div>
<div class="hideDiv">
<p>Can you see me</p>
</div>

Why can't I get the status of this radio button in jquery?

I have this piece of code from a salesforce visualforce page.
<div id="testId" class="row mb25 mt15">
<div class="col-md-6 plr0">
<p class="en">Would you like to add a co-applicant?<span class="asteriskField">*</span> </p>
<p class="fr">Would you like to add a co-applicant?<span class="asteriskField">*</span> </p>
</div>
<div class="col-md-4 mt-5r">
<apex:selectRadio id="innerTestId" value="{!client.Would_you_like_to_recieve_future_promo__c}" styleClass="radio">
<div class="row">
<div class="col-sm-6">
<div class="radio pa-cus">
<apex:selectOption itemLabel="Yes" itemValue="Yes"/>
</div>
</div>
<div class="col-sm-6">
<div class="radio pa-cus">
<apex:selectOption itemLabel="No" itemValue="No"/>
</div>
</div>
</div>
</apex:selectRadio>
</div>
</div>
When the Submit button is clicked I need to have a JQuery script to check weather the radio button is selected Yes or No so that I can perform some custom validation. I call this function by adding onclick="validateInnerTestId();" to Submit button.
My problem is that I am unable to read/check whether the radio button is chosen Yes or No or True or False. If I can find out what state they are in then I can do my
Here is my goal
<script type="text/javascript">
<script>
function validateInnerTestId()
{
if(innerTestId is Selected as Yes)
{
execute fucntionX()
}
else
{
execute functionY()
}
}
<script>
Here is some examples of how I have tried to read the value of the radio button:
alert($("#innerTestId").itemValue()); this line doesn't return anything
alert($("#innerTestId").val()); this line also doesn't return anything
and this if else always return no
if ($('innerTestId').is(':checked'))
{
alert("yes");
}
else
{
alert("no");
}
Does anyone has any idea on how to check for the radio button in this case?
Thanks
As #Andrea mentioned in the comments, you simply forgot the # in your selector. There is a simple example below demonstrating the usage. If your code still isn't working we will need more info.
Are you sure validateInnerTestId() is being called?
How is it being called?
$('#doit').on('click',function() {
var str = "";
if ($('#test').is(':checked')) {
str += "Toggle checked? YES\n"
} else {
str += "Toggle checked? NO\n"
}
if ($('#option1').is(':checked')) {
str += "Option checked: 1";
} else if ($('#option2').is(':checked')) {
str += "Option checked: 2";
} else {
str += "Option checked: NONE";
}
alert(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input id="test" name="toggle" type="checkbox" value="" />
<label for="toggle">Toggle</label>
</div>
<div>
<input type="radio" id="option1" name="options" value="1">
<label for="option1">Option 1</label>
<input type="radio" id="option2" name="options" value="2">
<label for="option1">Option 2</label>
</div>
<br />
<input id="doit" type="button" name="test" value="Tell me!" />
It might also be something to do with the ASP/SalesForce implementation? Perhaps some of the answers in this question might help: How to check if an option is selected?
VF tags use dynamic ids, you should do following:
function validateInnerTestId(){
if($('#{!component.innerTestId}').is(':checked')){
execute fucntionX()
}
else{
execute functionY()
}
}

Java Script not working in Internet Explorer

I have the following script where I calculate a price based on user input radio buttons and output it into a section of html. The script is not working in internet explorer properly.
var newprice = "";
function CalcPrice(){
// I take the input from the radio buttons here
var goals = $("#menu input[type='radio']:checked").val();
if (goals=="Weight Loss"){
newprice="45";
} else {
newprice="55";
}
$('.pricetotal').html("$"+newprice.toFixed(2));
}
HTML
<form class= "meal-table" id="meal-radio" onsubmit="return false">
<fieldset id="menu">
<input type="radio" id="radio01" name="menu" value="Weight Loss" />
<input type="radio" id="radio02" name="menu" value= "Performance"/>
</fieldset>
<div>
<div class="meal-plan-btn">
<button id="mealbtn" onclick="CalcPrice()">Add To Cart</button>
</div>
</div>
// this is where the price will be injected
<div class="pricebox" id="priceboxmobile">
<div class="pricetotal" >
<span ></span>
</div></div>
Changing this line
$('.pricetotal').html("$"+newprice.toFixed(2));
To:
$('.pricetotal').empty().html("$"+newprice.toFixed(2));

Saving RadioButtons locally

I have a code of multiple radio buttons (nested in tabs) and I need to save and restore all values locally. I tried with cookies but only one value was saved. I tried with "localStorage" but I think I need some help. The basic idea is to save the values on each click and restore them on "window.onload".
If it is easier I can go back to cookies! Any experience anyone? Thank you in advance.
<html>
<head>
<title>Saving RadioButtons locally</title>
</head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"> </script>
<script src="scripts/modernizr.js"></script>
<script type="text/javascript">
//this function runs everytime there is a click from the mouse to update and save the radio values (logicaly)
function saveState() {
//gets every object from the main form to read and save it.
localStorage.setItem("flag", "set");
var data = $("#mainform").serializeArray();
$.each(data, function(i, obj) {
localStorage.setItem(obj.name, obj.value);
});
console.log(data); //console shows only one object which is the first one (pid) with one value
}
//this function must be run each time the window loads to initialize the radio values (logicaly)
function onloadfunction() {
if (localStorage.getItem("flag") == "set") {
//gets every object from the main form to read and restore it.
var data = $("#mainform").serializeArray();
$.each(data, function(i, obj) {
$("[name='" + obj.name +"']").val(localStorage.getItem(obj.name));
});
}
}
window.onload=onloadfunction;
window.onbeforeunload=saveState;
//end of ideas...............
</script>
<body>
<form id="mainform" name='mainform'>
<div id="container" class="container">
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#Cid">Cid</a></li>
<li><a data-toggle="tab" href="#Bid">Bid</a></li>
<!-- first tab -->
<!-- first radio box in first tab -->
</ul>
<div class="tab-content">
<div id="Cid" class="tab-pane fade in active">
<form name='pid'>
<input type="radio" id="p40" name="p" value="40">40
<input type="radio" id="p45" name="p" value="45">45
<input type="radio" id="p50" name="p" value="50">50
</form>
<!-- second radio box in first tab -->
<form name='BName'>
<input type="radio" id="B40" name="B" value="40">40
<input type="radio" id="B45" name="B" value="45">45
</form>
</div>
<!-- second tab -->
<!-- first radio box in second tab -->
<div id="Bid" class="tab-pane fade">
<form name='HName'>
<input type="radio" id="H40" name="H" value="40">40
<input type="radio" id="H45" name="H" value="45">45
<input type="radio" id="H50" name="H" value="50">50
</form>
</div>
</form>
</body>

Categories

Resources