Show hide fieldsets greater than/less than on select change - javascript

I have a form which is going to contain 4 fieldsets. The user must fill in a minimum of 1 fieldset but can choose to complete additional fieldsets. Each fieldset's contents are identical.
I want them to be able to choose a number of fieldsets to show from a dropdown. On selecting a number from the dropdown the relevant number of fieldsets appears.
So if they choose 3 from the quantity dropdown, the first 3 fieldsets should be shown. If they change their mind and drop to 2 fieldsets then the 3rd should hide again.
Here's the base HTML.
<form>
<select id="quantity" name="quantity">
<option disabled="disabled">xx</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<fieldset id="fieldset_name_1">Form Area 1</fieldset>
<fieldset id="fieldset_name_2" style="display: none;">Form Area 2</fieldset>
<fieldset id="fieldset_name_3" style="display: none;">Form Area 3</fieldset>
<fieldset id="fieldset_name_4" style="display: none;">Form Area 4</fieldset>
</form>​
And here's my very basic jQuery so far. I'm quite a noob to client side stuff, generally burying my head in php :)
var registerCount = function() {
var qty = $(this).val();
var fieldsets = $('fieldset');
fieldsets.slice(0, qty ).show();
}
$("#quantity").change(registerCount).keypress(registerCount);
So I've got it showing fieldsets correctly, I'm just not sure how to hide them on change or keypress again.
I'm sure this is simple but I think my familiarity with PHP keeps me trying to code things completely differently to the jQuery/javascript way.

To hide the unselected, you hide all before showing the selected:
fieldsets.hide().slice(0, +qty).show();

Try hide all first and then show according to selection:
Sample:
var registerCount = function() {
var qty = $(this).val();
var fieldsets = $('fieldset');
fieldsets.each(function (){
$(this).hide();
});
fieldsets.slice(0, qty ).show();
}
$("#quantity").change(registerCount).keypress(registerCount);

You can put the fieldset dynamically to not hide them.
$(function(){
$('#quantity').change(function(){
$('#fieldsets').html('');
n = $(this).val();
for (i=1; i<=n; i++){
$('<fieldset/>', {
id: 'fieldset_name_'+i,
text: 'Form Area '+i
}).appendTo('#fieldsets');
}
});
})​
Demo: http://jsfiddle.net/JmeYZ/

Here is the answer,
http://jsfiddle.net/mQ23q/
Hope it will help

Related

Writing Conditional Drop Downs to MySQL

Hopefully this isn't too confusing..
I have a conditional form that has the user select a category, based on that category they'll need to choose from that category's sub categories. This works fine.
However, my issue is when writing to MySQL the Value that's inserted in my Sub Category column is always the last Select group's first Value (in this case it's "sandwich"). Example..
My Main Categories: Starters | Supper | Sandwiches
Starters' Sub Categories: Coastal or Southern
Supper's Sub Categories: Smokehouse or Specialties
Sanwiches' Sub Categories: Sandwich or Po-Boy
No matter which Category/Sub Category you select, it always writes the "Sandwich" subcategory in MySQL. Make sense?
So here's my code & JSFiddle if you want to play with the dropdowns. http://jsfiddle.net/kkobayashi/5f5tw4t0/
PHP to MySQL
<?php
if( isset( $_POST['create'] ) ):
$cat = $_POST['cat'];
$catsubs = $_POST['subcategory'];
$name = $_POST['name'];
$description = $_POST['description'];
$price = $_POST['price'];
mysql_query("INSERT INTO leDB (cat,subcategory)
VALUES('$cat','$catsubs')")
or die(mysql_error());
echo "Success."; /** success message **/
endif;
?>
HTML
<form action="" method="POST">
<!-- MAIN CATS -->
<select id="mainCat" class="source" name="cat">
<option value="starters">Starters</option>
<option value="supper">Supper</option>
<option value="sandwiches">Sandwiches</option>
</select>
<!-- SUB CATS -->
<div id="cat_starters" class="subcategory" style="display:inline;">
<select class="" id="starters" name="subcategory">
<option value="coastal">Coastal</option>
<option value="southern">Southern</option>
</select>
</div>
<div id="cat_supper" class="subcategory hidden">
<select class="" id="supper" name="subcategory">
<option value="smokehouse">Smokehouse</option>
<option value="specialties">Specialties</option>
</select>
</div>
<div id="cat_sandwiches" class="subcategory hidden">
<select class="" id="sandwiches" name="subcategory">
<option value="sandwich">Sandwich</option>
<option value="poboy">Po-Boys</option>
</select>
</div>
</form>
JS
// Conditional Drop Down
$(document).ready(function(){
$('#mainCat').on('change', function() {
// Setting this variable to add inline
var inline = document.querySelector('#cat_' + $(this).val() );
// Show/Hide
$('div.subcategory').hide();
$('#cat_' + $(this).val() ).show();
inline.style.display = "inline";
});
});
A little CSS
div.hidden {
display: none;
}
Don't know how well of a job I did describing the issue, if you're confused feel free to yell at me. Thanks y'all.
Hiding the select does not actually remove it from the DOM, as you would see if you would check the source. It only hides it from the user.
This means that every select with the same name attribute will override the last one, hence why you only get the last one.
an easy fix could be to add the name attribute to the correct select.
$(document).ready(function(){
$('#mainCat').on('change', function() {
// Setting this variable to add inline
var inline = document.querySelector('#cat_' + $(this).val() );
// Show/Hide
$('div.subcategory').hide().attr('name', '');
$('#cat_' + $(this).val() ).show().attr('name', 'subcategory');
inline.style.display = "inline";
});
});
you need to add unique names to your selects.
For example for starters, add name="starters". Add names as the option values of the category.
And after that, use: $catsubs = $_POST[$cat];
Change the subcategory names to maybe subcategory1, ...2 and ....3 or just make them unique in the form
You need the names to be unique. The reason you end up with the same sandwich no matter what you select is because you are using the same name. When the $_POST data is sent, it sends an array with the key equal to the name in the form. So to know exactly what a user clicked, selected or typed, each name must be unique

Show / Hide Form Elements based on Select

I'm trying to Show / Hide two elements based on a selection - a label and an input using Javascript getElementsByName. It works with getElementByID if I change things around on the label and input but for some reason Name isn't working. Here is the code:
<script language="JavaScript" type="text/javascript">
<!--
function Toggle(obj){
var val=obj.value;
if (!obj.m){ obj.m=''; }
if (!obj.m.match(val)){ obj.m+=','+val+','; }
var hide=obj.m.split(',');
for (var zxc0=0;zxc0<hide.length;zxc0++){
if (document.getElementsByName(hide[zxc0])){
document.getElementsByName(hide[zxc0]).style.display='none';
}
}
var show=val.split(',');
for (var zxc1=0;zxc1<show.length;zxc1++){
if (document.getElementsByName(show[zxc1])){
document.getElementsByName(show[zxc1]).style.display='';
}
}
}
//-->
</script>
and here are for form elements:
<div id="styled-select">
<select name="how" onchange="Toggle(this);" class="dropdown">
<option value="Internet Search">Internet Search</option>
<option value="Facebook" >Facebook</option>
<option value="Twitter" >Twitter</option>
<option value="LinkedIN" >LinkedIN</option>
<option value="Referral">Referral</option>
<option value="Other">Other</option>
</select>
</div>
<label name="Referral" style="display:none;">Referred By:</label>
<input name="Referral" style="display:none;" value="" class="hidden-txt">
When the user selects "Referal" it should display the Label and Input named "Referral". I had this working if I used getElementByID, gave the option two values separated by comma and used seperate IDs for the label and input.
Thank you for your help.
var elems = document.getElementsByName(hide[zxc0]);
if(elems) {
for(var i = 0;i < elems.length;i++) {
elems[i].style.display='none';
//Do whatever else you need to do with the element.
}
}
As mentioned by Kevin Boucher, getElementsByName returns an array. Assuming that you want to apply the display=none style to all elements with that name, the code above will achieve that. Also for performance's sake, the above code only calls document.getElementsByName() once as opposed to the 3+ times above which I'm sure will be beneficial.
It might be worth investigating JQuery for its ease of selecting elements.

Drop down product, put price in text field

I need to create a simple drop-down menu with 5 items (widget1, widget2, widget3, etc..) and a corresponding value which is the price. When the user clicks the 'Price button' after selecting the widget, I need the price to show up in the text box. This is what I've pulled from other snippets, but can't figure out the second part after the 'var x' to insert it into the text area.
function displayResult()
{
var x=document.getElementById("dropdown").value;
}
And the html...
<form action="">
<select id="dropdown" >
<option value="$1">widget1</option>
<option value="$2">widget2</option>
<option value="$3">widget3</option>
<option value="$4">widget4</option>
</select>
<button type="button" onclick="displayResult()">Price</button>
</form>
<textarea = id="showprice" size="10" maxlength="10"></textarea>
Most of the examples I've found change the text box after the drop down is selected, I need it work after the button is clicked. Thanks
You're so close already. Just reverse the process you used to get the value but use the id of the textbox and set its value property:
function displayResult() {
var x=document.getElementById("dropdown").value;
document.getElementById("showprice").value = x;
}
If that is the only thing that displayResult() does you don't need the x variable:
document.getElementById("showprice").value = document.getElementById("dropdown").value;

jQuery: Show/Hide Elements based on Selected Option from Dropdown

UPDATE: The original question asked was answered. However, the code revealed for all. So, I've modified my question below:
So I have the following dynamically generated html via php
<div class="image-link link-posttypes mainSelector1">
<select id="wp_accordion_images[20110630022615][post_type]" name="wp_accordion_images[20110630022615][post_type]">
<option value="">default</option>
<option value="post" class="post-type">Post</option><option value="page" class="post-type">Page</option><option value="dp_menu_items" class="post-type">Menu Items</option>
<option value="wps_employees" class="post-type">Employees</option><option value="custom-link">Custom Link</option>
</select>
</div>
<div class="image-link link-pages1">
<select id="wp_accordion_images[20110630022615][page_id]" name="wp_accordion_images[20110630022615][page_id]">
<option value="50" class="level-0">About</option>
<option value="65" class="level-0">Contact</option>
<option value="2" class="level-0">Sample Page</option>
<option value="60" class="level-0">Staff</option>
</select>
</div>
<div class="image-link link-posts1">
<select onchange="javascript:dropdown_post_js(this)" id="wp_accordion_images[20110630022615][post_id]" name="wp_accordion_images[20110630022615][post_id]">
<option value="http://localhost/tomatopie/?p=1" class="level-0">Hello world!</option>
</select>
</div>
<div class="image-link link-custom1">
<input type="text" size="25" value="" name="wp_accordion_images[20110630022615][image_links_to]">
</div>
***THEN IT REPEATS four times: where the #1 goes to 2..3...4 (max to 4 at this time).
I have the ability to label div .classes, select #ids, and option classes. However, what I want to be able to do is based on the option selected from div .link-posttypes, I want to reveal .link-pages (if page is selected) or .link-posts (if post is selected) and .link-custom for all others (except the default).
So as written on the screen there should only be the initial div, and once the user selects an item, the appropriate div appears.
I have never developed anything in jQuery or javascript. This is my maiden voyage. Any help will be greatly appreciated!
***Also, this will be loaded via an external js file.
Here is the final answer that worked:
jQuery(document).ready(function($) {
$(".link-posttypes select").change(function(){
var selectedVal = $(":selected",this).val();
if(selectedVal=="post"){
$(this).parent().nextAll(".link-pages").hide();
$(this).parent().nextAll(".link-posts").slideDown('slow');
$(this).parent().nextAll(".link-custom").hide();
}else if(selectedVal=="page"){
$(this).parent().nextAll(".link-pages").slideDown('slow');
$(this).parent().nextAll(".link-posts").hide();
$(this).parent().nextAll(".link-custom").hide();
}else if(selectedVal!=""){
$(this).parent().nextAll(".link-pages").hide();
$(this).parent().nextAll(".link-posts").hide();
$(this).parent().next().nextAll(".link-custom").slideDown('slow');
}else{
$(this).parent().nextAll(".link-pages").hide();
$(this).parent().nextAll(".link-posts").hide();
$(this).parent().nextAll(".link-custom").hide();
}
});
});
jQuery(document).ready(function($) {
$(".image-content select").change(function(){
var selectedVal = $(":selected",this).val();
if(selectedVal=="content-limit"){
$(this).parent().next().nextAll(".content-limit-chars").slideDown('slow');
$(this).parent().nextAll(".content-custom").hide();
}else if(selectedVal=="custom-content"){
$(this).parent().nextAll(".content-limit-chars").hide();
$(this).parent().next().nextAll(".content-custom").slideDown('slow');
}
});
});
Thanks for your help!
Assuming that you're outputting proper IDs, you can do something like this (note I replaced the id):
$(window).load(function(){
// hide all the divs except the posttypes
$('.image-link').not('.link-posttypes').hide();
$('#wp_accordion_images_20110630022615_post_type').change(function() {
var divSelector = '.link-' + $(this).val();
$('.image-link').not('.link-posttypes').hide();
$(divSelector).show();
});
});
Also, consider changing your options like this:
<option value="posts" class="post-type">Post</option>
<option value="pages" class="post-type">Page</option>
<option value="menu_items" class="post-type">Menu Items</option>
<option value="wps_employees" class="post-type">Employees</option>
<option value="custom">Custom Link</option>
Here's a jsfiddle for this: http://jsfiddle.net/JrPeR/
There's my understandable jquery script
jQuery(document).ready(function($) {
$(".link-pages").hide();
$(".link-posts").hide();
$(".link-custom").hide();
$(".link-posttypes select").change(function(){
var selectedVal = $(":selected",this).val();
if(selectedVal=="post"){
$(".link-pages").hide();
$(".link-posts").show();
$(".link-custom").hide();
}else if(selectedVal=="page"){
$(".link-pages").show();
$(".link-posts").hide();
$(".link-custom").hide();
}else if(selectedVal!=""){
$(".link-pages").hide();
$(".link-posts").hide();
$(".link-custom").show();
}else{
$(".link-pages").hide();
$(".link-posts").hide();
$(".link-custom").hide();
}
});
});
Demo here. Take me couple minute to make you easy to understand. Have fun.
http://jsfiddle.net/JrPeR/3/
added a conditional so if its not the two variables it defaults to the custom.

How to display image when click the select option using jquery, css

How to show an image while we select the option below.
Example : -
<select name="payment">
<option value="">Please Select</option>
<option value="Paypal">Paypal</option>
<option value="Bank">Bank</option>
</select>
<div id="payment"><img src="paypal.gif" alt="paypal" /></div>
If we select paypal on div id="payment" will show the logo paypal and if bank will show bank logo.
Can be done with jquery? let me know.
Assumption: your bank logo is called bank.gif.
EDIT: added code to check for blank value.
$('select[name=payment]').change(function() {
var val = $(this).val();
$('div#payment img')
.attr('src', val + '.gif')
.css('display', val.length ? 'block' : 'none');
});
Doh, misread the question, updated:
You can do this with just a small event handler, like this:
$(function() {
$("select[name=payment]").bind("change", function() {
$("#payment img").attr('src', $(this).val().toLowerCase() + ".gif");
}).change();
});
This approach adjusts the src of the image based on the current selected value. Also, we're triggering the event one time on document.ready to make the initial hide/show state match the dropdown.
You'll need to hide the paypal.gif first
<select name="payment">
<option value="Paypal">Paypal</option>
<option value="Bank">Bank</option>
</select>
<div id="payment"><img src="paypal.gif' alt="paypal' /></div>
Then bind a change handler to the select.
<script>
var images = {
'Paypal': 'paypal.gif',
'Bank': 'bankLogo.gif'
};
$("select").bind("change",function(){
$("div#payment img:first").attr('src', images[$("select :selected").val()] );
});
</script>

Categories