Conditional form actions with jquery show/hide on radios/inputs - javascript

I'm working on a form that has to show/hide based on a radio/checkbox selections. I have this half working, but I'm running into a number of errors & I'm certain that this code can be optimized/written much more efficiently.
The flow of the form needs to work based off of what checkboxes/radios are selected. I'm not entirely sure the best way to lay this out in a SO post, so Ive commented the html. If I can clarify this in anyway, I will happily do so if someone has a suggestion
In the markup below, I have added comments where I want to render the html. I have a working example of this over at JS Fiddle. You can see that here http://jsfiddle.net/gTAGG/2/
<form id="dorm-form" class="order-start form-horizontal form-horizontal-left-align" action="/reservation#hourly" method="GET">
<!-- SELECT school -->
<div class="control-group">
<label class="control-label" for="school">College town:</label>
<div class="controls">
<select name="school" class="span3">
<option value="">-- Choose your college town--</option>
{% for school in schools %}{% if school.name != 'Other' %}<option value="{{ school.id }}">{{ school.name }}</option>{% endif %}{% endfor %}
</select>
</div>
</div>
<!-- Multiple Checkboxes -->
<div class="control-group">
<p> Tell us what you need </p>
<label class="checkbox">
<input type="checkbox" name="checkboxes" value="Load">
Load
</label>
<label class="checkbox">
<input type="checkbox" name="checkboxes" value="Unload">
Unload
</label>
</div>
<!-- Multiple Checkboxes -->
<!-- values are still load & unload. Figure out how these save -->
<div id="movingtruck" class="control-group">
<p> Do you need a moving truck (flat rate $125) </p>
<label class="radio">
<input type="radio" name="radios" value="Yes" checked="checked">
Yes
</label>
<label class="radio">
<input type="radio" name="radios" value="No">
No
</label>
</div>
<!-- If you select either "load" or just "unload" this form should show. If both load & unload are selected, this does not show.-->
<div id="radios" class="control-group">
<p> Do you live in a dorm or greekhouse? </p>
<label class="radio">
<input type="radio" name="radios" value="Greek" checked="checked">
Yes
</label>
<label class="radio">
<input type="radio" name="radios" value="NoGreek">
No
</label>
</div>
<!-- if "yes" is selected above, then this should show. If "no" is selected above, this should hide.-->
<div id="dorms" class="control-group">
<label class="control-label" for="dorm">
<i class="error-warning cb-icon cb-icon-warning"></i>
Dorm:
</label>
<div class="controls">
<select require="true" name="dorm">
<option value="">-- Choose your dorm --</option>
{% for dorm in dorms %}<option value="{{ dorm.id }}">{{ dorm.name }}</option>{% endfor %}
</select>
</div>
</div>
<!-- if "yes" is selected above, then this should hide. If "no" is selected above, this should hide.-->
<div id="greek" class="control-group">
<label class="control-label">Greekhouse</label>
<div class="controls">
<input id="textinput" name="textinput" type="text" placeholder="name of your house" class="input-xlarge">
</div>
</div>
<!-- Show when "unload" is checked as well as when "no" selected. If "yes" is selected, this should hide -->
<div class="row" id="hops">
<div class="span6 control-group">
<label class="control-label" for="bellhops">
<i class="error-warning cb-icon cb-icon-warning"></i>
How many Bellhops?
</label>
<div class="controls">
<select name="bellhops">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
</select>
</div>
</div>
</div>
<!-- Show when "unload" is checked as well as when "no" selected. If "yes" is selected, this should hide -->
<div id="bellhop-hours" class="span6 control-group">
<label class="control-label" for="hours">
<i class="error-warning cb-icon cb-icon-warning"></i>
How many hours?
</label>
<div class="controls">
<select name="hours" id="hours">
<option value="1.5">One and a half</option>
<option value="2">Two</option>
<option value="2.5">Two and a half</option>
<option value="3">Three</option>
<option value="3.5">Three and a half</option>
<option value="4">Four</option>
<option value="4.5">Four and a half</option>
<option value="5">Five</option>
<option value="5.5">Five and a half</option>
<option value="6">Six</option>
<option value="6.5">Six and a half</option>
<option value="7">Seven</option>
<option value="7.5">Seven and a half</option>
<option value="8">Eight</option>
</select>
</div>
</div>
<!-- BUTTON -->
<div class="form-controls">
<button class="btn btn-lime">Reserve Your Bellhops!</button>
</div>
</form>
Here is the JS that I am using
// Inputs for Load & Unload
$("input[value=Load]").click(function(){
if($(this).is(":checked")){
$("#dorms, #greek,").show();
}else{
$("#dorms, #greek").hide();
}
});
$("input[value='Unload']").click(function(){
if($(this).is(":checked")){
$("#movingtruck").show();
}else{
$("#hops, #hours").hide();
}
});
// Inputs for Do you need a moving truck?
$("input[value='Yes']").click(function(){
if($(this).is(":checked")){
$("#hops, #bellhop-hours").show();
}
});
$("input[value='No']").click(function(){
if($(this).is(":checked")){
$("#hops, #bellhop-hours").show();
}
});
// Radios for "Do you live in a dorm or greekhouse?"
// Radios arent hiding when selecting "nogreek" Check on radios.
$("input[value='Greek']").click(function(){
if($(this).is(":checked")){
$("#dorms, #greek").show();
}else{
$("#dorms, #greek, #hops").hide();
}
});
$("input[value='NoGreek']").click(function(){
if($(this).is(":checked")){
$("#hops, #hours").show();
}else{
$("#dorms, #greek").hide();
}
});
And a tiny bit of CSS
/* Hiding form elements */
#greek, #dorm-selector, #hops, #dorms, #hidden, #movingtruck, #bellhop-hours{
display:none;
}

I have a work in progress fiddle which does something similar to yours (well, show and hide and add elements) You can check it out here: http://jsfiddle.net/Hux2L/
A question here: i'm not quite sure about your load and unload and do you want to show and hide accordingly? from what i see, after i clicked on something, something will show up but some won't show anything. ;) it's like a surprise game.
EDIT:
You can give the 2 checkboxes an ID each:
<input type="checkbox" name="checkboxes" value="Load" id="load">
<input type="checkbox" name="checkboxes" value="Unload" id="unload">
Then you can specify the condition as :
if ($('#load').is(':checked ')&&$('#unload').is(':checked')){
//do what you want here
$('#dorms').hide();
$('#movingtruck').show();
}

Related

if dropdown is selected span is to show attribute of that option. This works until I add a second Select input

$("#item1").change(function() {
$('#price-
displayitem1').text($('option:selected').attr('data-item1'));
}).change();
$("#item2").change(function() {
$('#price-displayItem2').text($('option:selected').attr('data-item2'));
}).change();
then here are the spans which will be chaged
<span id="price-displayItem1"></span>
<span id="price-displayItem2"></span>
Then here is the actual Select input
<div class="col-sm-3">
<label for="item1" style="color:black;">item1</label>
<div class="input-select">
<select name="item1" id="item1">
<option value="1" data-item1="1">1</option>
<option value="2" data-item1="2">2</option>
<option value="3" data-item1="3">3</option>
</select>
</div>
</div>
<div class="col-sm-3">
<label for="item2" style="color:black;">item2</label>
<div class="input-select">
<select name="item2" id="item2">
<option value="1" data-item2="1">1</option>
<option value="2" data-item2="2">2</option>
<option value="3" data-item2="3">3</option>
</select>
</div>
</div>
Note: the id's and name's in actuality are only using string characters
Explanation: so basically It works for the first item/dropdown/span. But when I introduce a second or even third, then only the first one works properly. If i remove the code of the first. Then the second one begins to work but still not the third. and so on.
I'd appreciate any help.
Thanks!
Well you use an option selector so you select all the options on the page.
$('option:selected').attr('data-item1')
so you need to look for the options in the select that you are using
$(this).find('option:selected').attr('data-item1')
You forgot to use selector before option.
$("#item1").change(function() {
$('#price-displayitem1').text($('#item1 option:selected').attr('data-item1'));
}).change();
$("#item2").change(function() {
$('#price-displayItem2').text($('#item2 option:selected').attr('data-item2'));
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="price-displayItem1"></span>
<span id="price-displayItem2"></span>
<div class="col-sm-3">
<label for="item1" style="color:black;">item1</label>
<div class="input-select">
<select name="item1" id="item1">
<option value="1" data-item1="1">1</option>
<option value="2" data-item1="2">2</option>
<option value="3" data-item1="3">3</option>
</select>
</div>
</div>
<div class="col-sm-3">
<label for="item2" style="color:black;">item2</label>
<div class="input-select">
<select name="item2" id="item2">
<option value="1" data-item2="1">1</option>
<option value="2" data-item2="2">2</option>
<option value="3" data-item2="3">3</option>
</select>
</div>
</div>

Check/uncheck radio buttons and hide option when uncheck

I have 2 radio buttons which when I click on one of them I get dropdown menu where must choose amount.
So far I was able to make it check/unchek them but the problem is that when I uncheck the radio button dropdown doesn't hide again.
I'm not very good in javascript so please help on this one. Here is the part of code
<div class="radio">
<label><input type="radio" autocomplete="off" id="paypal" name="paypal"></label> PayPal
</div>
<div class="radio">
<label><input type="radio" autocomplete="off" name="bank" id="bank"></label> Bank
</div>
<div class="form-group">
<span id="paypalamount" style="display:none">
<label class="col-sm-3 control-label" for="price"></label>
<div class="col-sm-9">
<div class="input-group">
<span class="input-group-addon">$</span>
<select id="paypalamount" required="required" class="form-control">
<option selected value="50">50</option>
</select>
</div>
</div>
</span>
<span id="bankamount" style="display:none">
<label class="col-sm-3 control-label" for="price">Please Choose Amount to Deposit</label>
<div class="col-sm-9">
<div class="input-group">
<span class="input-group-addon">$</span>
<select id="bankamount" required="required" class="form-control">
<option selected value="50">50</option>
<option value="100">100</option>
</select>
</div>
</div>
</div>
</span>
Here is JS
$(document).ready(function(){
$("#paypal").change(function(){
var showOrHide =$(this).is(':checked');
$("#paypalamount").toggle(showOrHide);
$('[name="description"]').toggleClass('#paypalamount',showOrHide )
});
$("#bank").change(function(){
var showOrHide =$(this).is(':checked');
$("#bankamount").toggle(showOrHide);
$('[name="description"]').toggleClass('#bankamount',showOrHide )
});
$("input[type='radio']").click(function()
{
var previousValue = $(this).attr('previousValue');
var name = $(this).attr('name');
if (previousValue == 'checked')
{
$(this).removeAttr('checked');
$(this).attr('previousValue', false);
}
else
{
$("input[name="+name+"]:radio").attr('previousValue', false);
$(this).attr('previousValue', 'checked');
}
});
});
And this is working demo of the code above JSFIDDLE
$(document).ready(function() {
$(":radio[name=bankpaypal]").change(function() {
if ($(this).is(':checked')) {
var name = $(this).attr('id')
$('span').hide()
$('span#' + name + 'amount').show()
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio">
<label>
<input type="radio" autocomplete="off" id="paypal" name="bankpaypal">
</label>PayPal
</div>
<div class="radio">
<label>
<input type="radio" autocomplete="off" name="bankpaypal" id="bank">
</label>Bank
</div>
<div class="form-group">
<span id="paypalamount" style="display:none">
<label class="col-sm-3 control-label" for="price"></label>
<div class="col-sm-9">
<div class="input-group">
<span class="input-group-addon">$</span>
<select id="paypalamount1" required="required" class="form-control">
<option selected value="50">50</option>
</select>
</div>
</div>
</span>
<span id="bankamount" style="display:none">
<label class="col-sm-3 control-label" for="price">Please Choose Amount to Deposit</label>
<div class="col-sm-9">
<div class="input-group">
<span class="input-group-addon">$</span>
<select id="bankamount1" required="required" class="form-control">
<option selected value="50">50</option>
<option value="100">100</option>
</select>
</div>
</div>
Name of radio button should be same to select only 1
ID should be unique
Get the selected radio button and show its counter select using its ID since they are similar
Use following code to check whether a radio button is checked or not
if($("input:radio[name=paypal]:checked").val())
alert("checked");
else
alert("Not checked");
Do your process of hiding and showing inside the if else conditions.
You only need to check for the value of a RadioButton as not checked. If unchecked set the style attribute display:none for the respective dropdown again in Javascript.
Just like you do it for the checked-Status of the RadioButton and just change the condition and the actions like you want the RadioButtons to behave.

selecting specific element within one parent

This is my HTML form structure:
EDIT: Each section is generated by PHP script, and the section id will change depending on user input. I am not able to use the whole selector because of this
<section id="JaneDoe">
<div class="gcolumn1">Jane Doe</div>
<div class="gcolumn2">Color:
<input type="radio" name="chk_clr[]" id="chk_clr[]" value="Y">Yellow
<input type="radio" name="chk_clr[]" id="chk_clr[]" value="R">Rose
<br>Food:
<input type="radio" name="JaneDoe-chk_food[]" id="chk_food[]" value="Y">Yes
<input type="radio" name="JaneDoe-chk_food[]" id="chk_food[]" value="N">No</div>
<div class="gcolumn3">
<select id="Meal[]" disabled>
<option value=""></option>
<option value="Chicken">Chicken</option>
<option value="Beef">Beef</option>
<option value="Vegetarian">Vegetarian</option>
<option value="Other">Other</option>
</select>
</div>
<div style="clear: both; height: 5px;"> </div>
<section id="JohnSmith">
<div class="gcolumn1">JohnSmith</div>
<div class="gcolumn2">Color:
<input type="radio" name="chk_clr[]" id="chk_clr[]" value="Y">Yellow
<input type="radio" name="chk_clr[]" id="chk_clr[]" value="R">Rose
<br>Food:
<input type="radio" name="JohnSmith-chk_food[]" id="chk_food[]" value="Y">Yes
<input type="radio" name="JohnSmith-chk_food[]" id="chk_food[]" value="N">No</div>
<div class="gcolumn3">
<select id="Meal[]" disabled>
<option value=""></option>
<option value="Chicken">Chicken</option>
<option value="Beef">Beef</option>
<option value="Vegetarian">Vegetarian</option>
<option value="Other">Other</option>
</select>
</div>
<div style="clear: both; height: 5px;"> </div>
</section>
I'd like for the dropdown Meal[] to be enabled only after the chk_food[] is selected as yes. However, I am having some trouble figuring out how to tell jQuery to enable only the dropdown box within the same section.
I currently have this as the jQuery: (I added the alert boxes to see which part of the code is not working)
var update_meal = function () {
alert ("Hi");
var sec_id = $(this).closest("section").attr("id");
alert (text(sec_id));
if ($(sec_id + "> #chk_food[]").is(":checked")) {
$(sec_id + "> #Meal[]").prop('disabled', false);
} else {
$(sec_id + "> #Meal[]").prop('disabled', 'disabled');
}
};
$(update_meal);
$("#chk_food[]").change(update_meal);
When I tried to run this on JSFiddle, no bugs show up, but the coding doesn't work at all.
I see the alert box popping up with "Hi" as soon as the document loads
Thank you for your help
You can't have multiple elements on the same page with the same ID. It is invalid HTML and it will confuse your code terribly. To get this to work, you first need to use classes to find things:
<section>
<div class="gcolumn1">JohnSmith</div>
<div class="gcolumn2">Color:
<input type="radio" name="chk_clr[]" value="Y">Yellow
<input type="radio" name="chk_clr[]" value="R">Rose
<br>Food:
<input type="radio" name="JohnSmith-chk_food[]" class="chk_food yes" value="Y">Yes
<input type="radio" name="JohnSmith-chk_food[]" class="chk_food no" value="N">No
</div>
<div class="gcolumn3">
<select name="Meal[]" class="meal" disabled>
<option value=""></option>
<option value="Chicken">Chicken</option>
<option value="Beef">Beef</option>
<option value="Vegetarian">Vegetarian</option>
<option value="Other">Other</option>
</select>
</div>
<div style="clear: both; height: 5px;"> </div>
</section>
Then you can start to target things correctly. Something like this:
$(".chk_food").on("change", function() {
$(this)
.closest("SECTION")
.find("SELECT.meal")
.prop("disabled", $(this).is(".no"));
});
In this case, we bind the change handler on both the Yes and No food radios. The handler will be called for the one the user clicks on, so they are inherently turning that one "on". So we find the parent section, and then the meal select within it, and set its disabled property to true if this is the .yes radio and false if this is the .no radio.
I think that should do it.

Show form based on radio button select [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have the following html which has two forms with form id=cardpayment for first form and form id="intenetpayment" for the second.
Also I have 3 radio buttons named "Debit card","Credit Card","Internet Banking".
All I want to do is,when I select the radio button Debitcard or Credit card,form with id="cardpayment" should be shown and the other form should be hidden and when i click on Internetbanking radio button , form with id="cardpayment" should be hidden and form with id="internetpayment" should be shown. Im new to jquery and javascript.I checked online that this can be done using a css by adding/removing a css class
{
display:none;
}
But i dont know how to make it work using javascript.
You can find the fiddle at http://jsfiddle.net/d5qDb/1/
Pardon for the long question,and I havnt included the css here for not confusing the question.It is in the fiddle anyway.thanks in advance for any help.I have given the division to two forms below.
<body>
<div id="credit-card">
<header>
<span class="title" style="background-image: url('images/fethrpowered.png');"><strong>Card Payment:</strong> Enter payment details</span>
<span class="close"><img src="images/close.png"/></span>
</header>
<section id="content">
<div class="title"><strong>Payment Mode- Select your payment mode</strong></div>
<input type="radio" id="radio1" name="radios" value="all" checked>
<label for="radio1">Credit Card</label>
<input type="radio" id="radio2" name="radios"value="false">
<label for="radio2">Debit Card</label>
<input type="radio" id="radio3" name="radios"value="false">
<label for="radio3">Internet Banking</label>
<form method="post" id="cardpayment">
<div style="float:right;margin-top:50px;">
<input type='hidden' id='ccType' name='ccType' />
<ul class="cards">
<li class="visa">Visa</li>
<li class="visa_electron">Visa Electron</li>
<li class="mastercard">MasterCard</li>
<li class="maestro">Maestro</li>
</ul>
</div>
<div class="table form-fields">
<div class="row">
<div class="label">Card Number:</div>
<div class="input full"><input type="text" name="ccnumber" id="ccnumber" placeholder="8763125487533457"/><br/></div>
</div>
<div class="row">
<div class="label">Card Type:</div>
<div class="input full">
<select class="styled">
<option selected>Visa</option>
<option>Mastercard</option>
<option>Maestro</option>
<option>SBI Maestro</option>
</select>
</div>
<div class="valid"></div>
</div>
<div class="row">
<div class="label">Your name:</div>
<div class="input full"><input type="text" name="name" id="name" placeholder="Mr. Personality of TV"/></div>
</div>
<div class="row name">
<div class="label">Expires On:</div>
<div class="input size50">
<select class="styled">
<option selected>Select Month</option>
<option value="01">January</option>
<option value="02">February</option>
<option value="03">March</option>
<option value="04">April</option>
<option value="05">May</option>
<option value="06">June</option>
<option value="07">July</option>
<option value="08">August</option>
<option value="09">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select class="styled">
<option selected>Select Year</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
<option value="2022">2022</option>
<option value="2023">2023</option>
<option value="2024">2024</option>
<option value="2025">2025</option>
<option value="2026">2026</option> <option value="2027">2027</option>
<option value="2028">2028</option>
<option value="2029">2029</option>
<option value="2030">2030</option>
<option value="2031">2031</option>
<option value="2032">2032</option>
<option value="2033">2033</option>
<option value="2034">2034</option>
<option value="2035">2035</option>
<option value="2036">2036</option>
</select>
</div>
<div class="valid"></div>
</div>
<div class="row name">
<div class="label">CVV Number:</div>
<div class="input size50"><input type="text" name="cvv" id="cvv" placeholder="490" maxlength="3"/></div>
</div>
</div>
<input type="submit" style="float:right" value="Pay Now"/>
</form>
<form method="post" id="internetpayment">
<div class="table form-fields">
<div class="row name">
<div class="label">Name:</div>
<div class="input full"><input type="text" name="name" id="Name" placeholder="Enter your name"/></div>
</div>
<div class="row name">
<div class="label">Email:</div>
<div class="input full"><input type="text" name="email" id="email" placeholder="Enter Email address"/></div>
</div>
<div class="row name">
<div class="label">Mobile Number:</div>
<div class="input size50"><input type="text" name="Mobile Number" id="mobileNo"/></div>
</div>
<div class="row name">
<div class="label">Bank:</div>
<div class="input size50">
<select name="BankId" class="styled" data-required="true" data-trigger="change">
<option value="CORP">Corporation </option>
<option value="HDFC"> HDFC </option>
<option value="ICICI"> ICICI </option>
<option value="IDBI"> IDBI </option>
<option value="SBI"> STATE BANK OF INDIA </option>
<option value="DB"> DEUTSCHE </option>
</select>
</div>
<div class="valid"></div>
</div>
<div class="row name">
<div class="label">Amount:</div>
<div class="input size50"><input type="text" name="amount" id="amount" placeholder="10.00"/></div>
</div>
</div>
<input type="submit" style="float:right" value="Pay Now"/>
</form>
</section>
</div>
</body>
Using pure JavaScript:
Write this in your Script section.
var radios = document.getElementsByName("radios");
var cardpayment = document.getElementById("cardpayment");
var internetpayment = document.getElementById("internetpayment");
/* If Credit Card is selected by default, add these two lines of code.
cardpayment.style.display = 'block'; // show
internetpayment.style.display = 'none';// hide
*/
for(var i = 0; i < radios.length; i++) {
radios[i].onclick = function() {
var val = this.value;
if(val == 'radio1' || val == 'radio2'){ // Assuming your value for radio buttons is radio1, radio2 and radio3.
cardpayment.style.display = 'block'; // show
internetpayment.style.display = 'none';// hide
}
else if(val == 'radio3'){
cardpayment.style.display = 'none';
internetpayment.style.display = 'block';
}
}
}
fiddle: http://jsfiddle.net/LbrCf/
Try this, using jQuery Onchange
$("#radio1, #radio2").on("change", function(){
$("#cardpayment").show();
$("#internetpayment").hide();
});
$("#radio3").on("change", function(){
$("#cardpayment").hide();
$("#internetpayment").show();
});
I added this JavaScript code into your JSFiddel to create that effect
$('#radio1').change(function() {
if(this.checked) {
$('#cardpayment').show();
$('#internetpayment').hide();
}
});
$('#radio2').change(function() {
if(this.checked) {
$('#internetpayment').show();
$('#cardpayment').hide();
}
});
Your jQuery code should look something like this:
$(document).ready(function(){
$('#internet_radio').on('click', function(){
$('#cardpayment').hide();
$('#internetpayment').show();
})
$('#debit_radio').on('click', function(){
$('#cardpayment').show();
$('#internetpayment').hide();
})
})
Don't forget to load jQuery libraries to make this work.
Also the next time you need this type of functionality, you could use this. You don't really have to load their css files, only the js libraries, and you can style your tabs as you like.
Pretty simple. Just do this:
$("#radio1, #radio2").on("click", function(){
$("#cardpayment").show();
$("#internetpayment").hide();
});
$("#radio3").on("click", function(){
$("#cardpayment").hide();
$("#internetpayment").show();
});

Drop down list - display div when clicking an option

You must write a function that 'shows' the corresponding part of the form depending on what the user has selected. For example, if 'Pizza' is selected, the div #section2 with the question about Pizza type should be shown.
This is part of the html code
<form id="survey" action="#" method="post">
<div id="section1">
<label for="food">What is your favourite type of food?</label>
<select id="food" onchange="selection()">
<option value="pizza">Pizza</option>
<option value="mex">Mexican</option>
<option value="thai">Thai</option>
</select>
</div>
<div id="section2">
What is your favourite type of pizza?<br>
<label for="hawaiian">Hawaiian</label><input type="radio" id="hawaiian">
<label for="supreme">Supreme</label><input type="radio" id="supreme">
<label for="vegetarian">Vegetarian</label><input type="radio" id="vegetarian">
</div>
How would i write a javascript function so that when I click the option pizza, it will display section 2? I'm a complete javascript novice so any help would be great.
DEMO: http://jsfiddle.net/iambriansreed/rQr6v/
JavaScript:
var sections = {
'pizza': 'section2',
'mex': 'section3',
'thai': 'section4'
};
var selection = function(select) {
for(i in sections)
document.getElementById(sections[i]).style.display = "none";
document.getElementById(sections[select.value]).style.display = "block";
}
Checkout the demo. Replace the section3 and section4 divs with actual content.
There are plenty of solutions for that. One of the simpliest options is to change your markup a bit and use div IDs.
HTML:
<div id="section1">
<label for="food">What is your favourite type of food?</label>
<select id="food" onchange="selection(this)">
<option value="pizza">Pizza</option>
<option value="mex">Mexican</option>
<option value="thai">Thai</option>
</select>
</div>
<div id="section_pizza" style="display: none;">
What is your favourite type of pizza?<br>
<label for="hawaiian">Hawaiian</label><input type="radio" id="hawaiian">
<label for="supreme">Supreme</label><input type="radio" id="supreme">
<label for="vegetarian">Vegetarian</label><input type="radio" id="vegetarian">
</div>
JavaScript:
function selection(select) {
document.getElementById("section_" + select.value).style.display = "block";
}
However, you can use JQuery library and make it faster and more flexible. You can easily add animation to blocks and add extra functionality.
HTML:
<div id="section1">
<label for="food">What is your favourite type of food?</label>
<select id="food">
<option value="pizza">Pizza</option>
<option value="mex">Mexican</option>
<option value="thai">Thai</option>
</select>
</div>
<div id="section2" data-type="pizza" style="display: none;">
What is your favourite type of pizza?<br>
<label for="hawaiian">Hawaiian</label><input type="radio" id="hawaiian">
<label for="supreme">Supreme</label><input type="radio" id="supreme">
<label for="vegetarian">Vegetarian</label><input type="radio" id="vegetarian">
</div>
JavaScript:
$("#food").change(function() {
$("[data-type]").hide();
$("[data-type='" + this.value + "']").show(1000);
});

Categories