Show/hide fields depending on select value - php

I am trying to show and hide a few form fields depending on the value of one of my select fields. I am looking to use arrays to hold what should be shown and what should not be shown for each select value, to save me from a massive switch statement, but cannot figure out how to do it.
I am using PHP and jQuery. Any help would be great.

Try something like this:
<select id="viewSelector">
<option value="0">-- Select a View --</option>
<option value="view1">view1</option>
<option value="view2">view2</option>
<option value="view3">view3</option>
</select>
<div id="view1">
<!-- content -->
</div>
<div id="view2a">
<!-- content -->
</div>
<div id="view2b">
<!-- content -->
</div>
<div id="view3">
<!-- content -->
</div>
then in the jQuery:
$(document).ready(function() {
$.viewMap = {
'0' : $([]),
'view1' : $('#view1'),
'view2' : $('#view2a, #view2b'),
'view3' : $('#view3')
};
$('#viewSelector').change(function() {
// hide all
$.each($.viewMap, function() { this.hide(); });
// show current
$.viewMap[$(this).val()].show();
});
});

There are a few different ways you could do this. The simplest is to have a few separate fieldsets, each one containing a single group of fields. Then, in jQuery, dependent on the select-menu's value you can show/hide these fieldsets, e.g.
<fieldset id="f1">
<input name="something1" />
<input name="something2" />
<input name="something3" />
</fieldset>
<fieldset id="f2">
<input name="something4" />
<input name="something5" />
<input name="something6" />
</fieldset>
<select name="fieldset-choice">
<option value="f1">Fieldset 1</option>
<option value="f2">Fieldset 2</option>
</select>
<script type="text/javascript">
jQuery('select[name=fieldset-choice]').change(function(){
var fieldsetName = $(this).val();
$('fieldset').hide().filter('#' + fieldsetName).show();
});
// We need to hide all fieldsets except the first:
$('fieldset').hide().filter('#f1').show();
</script>
Note: For the above technique to be entirely unobtrusive you might want to dynamically build the select-menu with the names of all the different fieldsets.
Alternatively you can prefix each fields name with a meaningful prefix, and then hide/show according to that attribute:
<input name="group1-name1" />
<input name="group1-name2" />
<input name="group2-name3" />
<input name="group2-name4" />
<input name="group2-name5" />
<select name="field-choice">
<option value="group1">Group 1</option>
<option value="group2">Group 2</option>
</select>
<script type="text/javascript">
jQuery('select[name=field-choice]').change(function(){
var groupName = $(this).val();
$('input').hide().filter('[name^=' + groupName + ']').show();
});
// We need to hide all fields except those of the first group:
$('input').hide().filter('[name^=group1]').show();
</script>

To fire up the code on load, just add .change(). As shown below...
$(document).ready(function() {
$.viewMap = {
'0' : $([]),
'view1' : $('#view1'),
'view2' : $('#view2a, #view2b'),
'view3' : $('#view3')
};
$('#viewSelector').change(function() {
// hide all
$.each($.viewMap, function() { this.hide(); });
// show current
$.viewMap[$(this).val()].show();
}).change();
});

My 2 cents :
I needed to show/hide fields depending on many previous select value (not only one).
So I add a parent attribute to div fields like this :
<div id="view" parent="none">
<select class=selector id="view">
<option value="0"> -- Make a choice --</option>
<option value="s1">sub 1</option>
<option value="s2">sub 2</option>
<option value="s3">sub 3</option>
</select>
</div>
<!-- you need to define the parent value with the value of parent div id -->
<div id="s1" parent="view">
<!-- if you want to have a selector be sure it has the same id as the div -->
<select class=selector id="s1">
<option value="0">-- Make a choice --</option>
<option value="s1_sub1">sub 1 of s1</option>
<option value="s1_sub2">sub 2 of s1</option>
<option value="s1_sub3">sub 3 of s1</option>
</select>
</div>
<!-- Make the same thing for s2 and s3
Define div s2 here
Define div s3 here
-->
<!-- and finally if that's your final step you put what you want in the div -->
<div id="s1_sub1" parent="s1">
You are inside s1 sub1
</div>
Now the jquery code :
$(document).ready(function() {
$('select[class=selector]').change(function() {
//next div to show
var selectorActive = $(this).val();
//div where you are
var parentValue = $(this).attr("id");
//show active div and hide others
$('div').hide().filter('#' + selectorActive).show();
while (parentValue!="none") {
//then show parents of active div
$('div[id=' + parentValue + ']').show();
//return the parent of div until "none"
parentValue = $('div[id=' + parentValue + ']').attr("parent");
}
});
// print only the first div at start
$('div').hide().filter("#view").show();
});
That's works like a charm and you don't need to define maps
I hope this will help

#Martin Try this
`$('#viewSelector').trigger('change');`

Here is a very simple example:
The purpose is to show A SIMPLE EXAMPLE of how to use an array of values to show/hide fields depending upon the value of a select.
In this demo, I could have used the classNames to show/hide the group of fields all-at-once -- but that's not the purpose of the example -- so the classNames were used only for CSS.
Because the demo uses IDs (with two arrays of these IDs) for the demo, it doesn't matter whether the fields to be hidden are input fields, divs, imgs or what-have-you. The ID identifies whatever-it-is-to-be-hid.
var aPeople = ['bob','sam','ted'];
var aTransport = ['car','bike','truck'];
$('#mySel').change(function(){
$('.alldiv').hide(); //Hide them all to start...
let sel = $(this).val(); //Get selected option value
if ( sel=='ppl' ){
for (let i=0; i<aPeople.length;i++){
$('#' + aPeople[i]).show();
}
}else if ( sel=='tpt' ){
for (let i=0; i<aTransport.length;i++){
$('#' + aTransport[i]).show();
}
}else{
//Choose selected
$('.alldiv').show();
}
});
.alldiv{width:30vw;height:10vh;padding:2vh 2vw;text-align:center;}
.ppl{background:palegreen;}
.tpt{background:wheat;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<select id="mySel">
<option value="">Choose:</option>
<option value="ppl">People</option>
<option value="tpt">Vehicles</option>
</select>
<div id="bob" class="alldiv ppl">People: Bob</div>
<div id="car" class="alldiv tpt">Vehicle: Car</div>
<div id="truck" class="alldiv tpt">Vehicle: Truck</div>
<div id="sam" class="alldiv ppl">People: Sam</div>
<div id="ted" class="alldiv ppl">People: Ted</div>
<div id="bike" class="alldiv tpt">Vehicle: Bike</div>

Related

How to have an HTML input field appear when the value 'other' is selected with PHP

What I am trying to figure out is how to have an html input field appear when the value of other is selected from a dropdown menu. Right now the values for the dropdown list are coming from the results of a MySQL DB query, which works, but I can not seem to figure out how to get an input to appear when I select the other option.
$query = mysql_query("SELECT type FROM Dropdown_Service_Type"); // Run your query
echo '<select name="service_type">'; // Open your drop down box
echo '<option value="NULL"></option>';
// Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query)) {
echo '<option value="'.$row['type'].'">'.$row['type'].'</option>';
}
echo '<option value="Other">Other</option>';
echo '</select>';// Close your drop down box
Use javascript, like in the example below. We can add an input field and have it hidden by default, using the style attribute:
<input name='otherInput' id='otherInput' type="text" style="display: none" />
var otherInput;
function checkOptions(select) {
otherInput = document.getElementById('otherInput');
if (select.options[select.selectedIndex].value == "Other") {
otherInput.style.display = 'block';
}
else {
otherInput.style.display = 'none';
}
}
<select onchange="checkOptions(this)" name="service_type" id="service_type">
<option value="NULL"></option>
<option value="43">43</option>
<!-- other options from your database query results displayed here -->
<option value="Other">Other</option>
</select>
<!-- the style attribute here has display none initially, so it will be hidden by default -->
<input name='otherInput' id='otherInput' type="text" style="display: none" />
There are 3rd party libraries like jQuery, AngularJS, PrototypeJS, etc., which can be used to make the code simpler by adding shortcut methods for DOM manipulation (though you should read this post). For example, with jQuery, using .on() (for the event handler binding), .show() and .hide() for the input display toggling, etc:
var otherInput;
var serviceTypeInput = $('#service_type');
serviceTypeInput.on('change', function() {
otherInput = $('#otherInput');
if (serviceTypeInput.val() == "Other") {
otherInput.show();
} else {
otherInput.hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="service_type" id="service_type">
<option value="NULL"></option>
<option value="43">43</option>
<option value="Other">Other</option>
</select>
<input name='otherInput' id='otherInput' type="text" style="display: none" />
$(function() {
$('#sample').change(function() {
var val = this.value; // get the value of the select.
if (val == 'other') { // if the value is equal to "other" then append input below the select
$('html').append('<input type="text" id="inputOther"/>');
} else { // else then remove the input
$('#inputOther').remove();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sample">
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test3">test3</option>
<option value="other">other</option>
</select>

calculating sums for dynamically added form elements

I have below form, where each .form-row is dynamically added using jQuery when user clicks on Add New button.
My html form (simplified)
<div id="total_sum">
<!-- here will show up total amount, which is sum of unit[] * price[] - discount[] of all below form-rows -->
</div>
<div id="total_discount">
<!-- here will show up total discount amount, which is sum of discount[] of all below form-rows -->
</div>
<div id="total_net">
<!-- here will show up net amount, which is total_sum - total_discount -->
</div>
<form id="form" method="POST" action="">
<div class="form-row">
<select name="item[]">
<option value="item-id-1">Item 1</option>
<option value="item-id-2">Item 2</option>
<option value="item-id-3">Item 3</option>
</select>
<input type="number" class="unit" value="1" name="unit[]" />
<input type="number" class="price" name="price[]" />
<input type="number" class="discount" name="discount[]" />
<input type="number" class=name="sum[]" />
</div>
<div class="form-row">
<select name="item[]">
<option value="item-id-1">Item 1</option>
<option value="item-id-2">Item 2</option>
<option value="item-id-3">Item 3</option>
</select>
<input type="number" class="unit" value="1" name="unit[]" />
<input type="number" class="price" name="price[]" />
<input type="number" class="discount" name="discount[]" />
<input type="number" class="sum" name="sum[]" />
</div>
<!-- and users can dynamically add as many form-rows as they want -->
<div class="form-row">
<select name="item[]">
<option value="item-id-1">Item 1</option>
<option value="item-id-2">Item 2</option>
<option value="item-id-3">Item 3</option>
</select>
<input type="number" class="unit" value="1" name="unit[]" />
<input type="number" class="price" name="price[]" />
<input type="number" class="discount" name="discount[]" />
<input type="number" class="sum" name="sum[]" />
</div>
</form>
And what I am trying to achieve is two-folded:
calculate the sum of each line (.form-row) and display the sum in each line (in sum[] field)
calculate the sum of all sums and discounts of all lines (all .form-rows) and display them in #total_sum, #total_discount, and #total_net.
I believe I need something that gets all .form-rows, which is triggered whenever there is a change in the form (or every 1 second, perhaps?), and loop through them to calculate respective sum, and calculate the total of sums and discounts when looping is over. I can do this if it's PHP, but I am quite new to jQuery or Javascript so I have no idea where to look into first.
[Adddd]
One thing I did not mention in above explanation is that unit[] has default value of 1 and price[] is at first automatically appended using AJAX, and then users can change the value.
My AJAX to automatically retrieve price when user selects an item.
<script>
jQuery(document).ready(function($) {
/* Get Item Price and Item Currency */
$('#form').on('change', '.item_id', function(){
var this$ = $(this);
var $item_id = this$.val();
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
// call ajax for item price (returns 0 if item has no price)
$.ajax({
url: ajaxurl,
data:' action=get_item_price_by_id&item_id='+$item_id,
type:'GET',
success:function(results) {
this$.parent().parent().find('.price').empty();
this$.parent().parent().find('.price').val(results);
}
});
});
});
</script>
Thanks to the advice from Manish Jangir Blogadditic, I came to have below code:
<script>
jQuery(document).ready(function($) {
// Calculate sub-sums on any form changes
$("#form").change(function() {
var sum = 0;
$('.form-row').each(function() {
sum = Number( $(this).find('unit').val()) * Number( $(this).find('price').val() );
alert( sum );
});
});
});
</script>
However, it works when the form is manually changed, but doesn't work when price is automatically appended by ajax.
Any other suggestions?
If your button #form comes with the last added dynamic element then you can try this out because .change or .on don't work with dynamically appended html elements. jQuery has given a $(document).on event to do that.
jQuery(document).ready(function($) {
// Calculate sub-sums on any form changes
$(document).on('click','#form',function() {
var sum = 0;
$('.form-row').each(function() {
sum += Number( $(this).find('.unit').val()) * Number( $(this).find('.price').val() );
alert( sum );
});
});
});
Value changed by Javascript will not trigger onchange event. And this rule applied on JQuery's change function too. So you may need to manually trigger onchange event after the updating. With Jquery you may use .trigger(), check here: http://api.jquery.com/trigger/
Try this code it will resolve your issue.
jQuery(document).ready(function() {
// Calculate sub-sums on any form changes
$("#form").on('change',function() {
var sum = 0;
$('.form-row').each(function() {
sum += parseInt($(this).find('.unit').val()) + parseInt($(this).find('.price').val());
});
});
});
You have to create a delegated event.
jQuery(document).ready(function() {
// Calculate sub-sums on any form changes
$("#form").on('change','.price, .unit',function() {
var sum = 0;
$('.form-row').each(function() {
sum = Number( $(this).find('.unit').val()) * Number( $(this).find('.price').val() );
alert( sum );
});
});
});

How to create a text box after selecting an option from drop-down list?

I'm trying to create a drop-down list with four options such that if I select the 4th option, I want a text box created so that I can get the value typed in that box using "$_GET"
Something like this;
<select name="value">
<option value="value1">Option 1</option>
<option value="value2">Option 2</option>
<option value="value3">Option 3</option>
<!-- And a 4th one -->
</select>
And if the 4th one is selected, a box should appear like this;
<input type="text" name="firstname">
Edit;
My current code;
<script>
jQuery(function($){ //calling the code inside braces when document loads and passing jQuery object as '$' parameter;
$("select[name='sortby']").change(function(){ //binding an event that fires every time select value changes
var select = $(this); //caching select, which value was changed
if(select.val() === "byDefindex"){ //checking if we selected the right option
$("<input>").attr({type: "text", name: "defindex"}).appendTo(select.parent()); //creating new input element object, setting its value to "value4" and appending to select parent element or wherever you want it
}
});
});
</script>
<form action="<?php $_PHP_SELF ?>" method="GET">
Select:
<br />
<select name="sortby">
<option value="playHours">Play Hours</option>
<option value="lastLogin">Last Login</option>
<option value="byDefindex">By Defindex</option>
</select>
<br />
<input type="submit" />
</form>
If your 4th option is this:
<option value="value4">Option 4</option>
You can use jQuery to display the field.
Put your field in a <div>
<div id="field"><input type="text" name="firstname"></div>
Now,
<script type="text/javascript">
$(document).ready(function(){
$('input[name="value"]').change(function(){
var v = $('input[name="value"]').val();
if(v=="value4") $('#field').show();
else $('#field').hide();
})
})
This is usually done via javascript; something like this (by using popular JavaScript library, jQuery) :
jQuery(function($){ //calling the code inside braces when document loads and passing jQuery object as '$' parameter;
$("select[name='value']").change(function(){ //binding an event that fires every time select value changes
var select = $(this); //caching select, which value was changed
if(select.val() === "value4"){ //checking if we selected the right option
$("<input>").attr({type: "text", name: "firstname"}).appendTo(select.parent()); //creating new input element object, setting its value to "value4" and appending to select parent element or wherever you want it
}
});
});
Hope that helps. You can find more here jQuery site
I'm not certain this is what you're asking, but it seems you're wanting to add new lines to your select list?
I often do something similar to this for adding new options to lists. The first option would be 'add a new record', like this:
<select name="value">
<option value="-1">Add New Option</option>
<option value="value1">Option 1</option>
<option value="value2">Option 2</option>
<option value="value3">Option 3</option>
</select>
Note that the value for "add new" is -1... you could put anything here, but it should be something that would never show up in the other options, so your javascript knows what to do when it is selected.
Add a 'onchange' to the select box like this:
<select name="value" onchange="if(this.value == -1) addOption(this);">
Note that if the selected option is -1, then a javascript function is called. It references itself (this), so that your function knows who called it.
Then create a function that allows adding a new option:
function addOption(theSelectElement){
// create a text box, underneath the select box:
var newInput=document.createElement('input');
newInput.type='text';
theSelectElement.parentNode.insertAfter(newInput,theSelectElement);
}
You'll want to add more code to this function so that the new text field has a name and perhaps an ID.
Hope this helps, or at least points you in the right direction.

change the size of div by selecting value from the dropdown

i have a dropdown where there is a value of pixels and below is a div with some data and
the div is of some width and height but what i need to do is when i select any value lets
suppose i selct 350px then the size of the div should automatically adjust accordingly. i
dont have any idea how to do that refer me any link so that i could get help from there.
i am serching for it or any kind of help on google for the last one hour.
here is the html
<td>
<select name="sizi_pixel" id="drp">
<option value="1">100 Pixels</option>
<option value="2">200 Pixels</option>
<option value="3">350 Pixels</option>
<option value="4">450 Pixels</option>
<option value="5">600 Pixels</option>
</select>
</td>
and here is the div i want to resize automatically
<div style=" border-width:3px;border-style:solid;border-color:#ff9900; height:400px; width:300px">
<input class="color" value="999">
<input class="color" value="999">
<input class="color" value="999">
</div>
any help will be appreciated
This javascript should do the trick!
You need to attach an event listener to your select input, also change the options to represent the value in the box. And give your div an id, I gave it the id 'myDiv'.
you can also see it working here: http://jsfiddle.net/6avqc/1/
document.getElementById('drp').addEventListener('change', changeSize);
function changeSize() {
var myDiv = document.getElementById('myDiv');
var selectbox = document.getElementById('drp');
var index = selectbox.selectedIndex;
var value = selectbox[index].value;
myDiv.style.width = value + 'px';
}​
Give your div an id and add an event listener for the change Event of your list view. Everytime the event is raised, you can change the size of the list
<script>
$(function() {
$("#drp").change(function() {
$("#rect").width($(this).val() + "px");
});
});
</script>
you have to include jquery in your page and modify the vals of your list to match the widths
Here is an working example if you have additional questions feel fre to ask:
Jsfiddle DEMO: http://jsfiddle.net/kPFry/
<html>
<head>
<style>
input {
position: relative;
width: 90%;
}
</style>
<script>
function chng_div(src_id,div_id){
var src_obj = document.getElementById(src_id);
var div2chg = document.getElementById(div_id);
div2chg.style.width = src_obj.value+"px";
}
</script>
</head>
<body>
<select name="sizi_pixel" id="drp" onchange="chng_div('drp','div_to_chng');">
<option value="100">100 Pixels</option>
<option value="200">200 Pixels</option>
<option value="350">350 Pixels</option>
<option value="450">450 Pixels</option>
<option value="500">600 Pixels</option>
</select>
<div style="border-width:3px;border-style:solid;border-color:#ff9900; height:400px; width:300px" id="div_to_chng">
<input class="color" value="999">
<input class="color" value="999">
<input class="color" value="999">
</div>
</body>
</html>
this is just an example, please do not use inline CSS styles ever long term it would cost you too much.

Using a jQuery effect to change the contents of a div?

I am having a form and I would like to change it's contents based on the selected value of a drop down list. All the following will be used in a PHP file.
It looks like this:
<style type="text/css">
.hide {
display:none;
}
<select>
<option value="" >Please select product below</option>
<option value="pro1">Product 1</option>
<option value="pro2">Product 2</option>
</select>
<div id="pro1" class="hide" >Product 1</div>
<div id="pro2" class="hide" >Product 2</div>
A suggested solution is the following
You can use the slideUp() and slideDown built-in effect.
Or any of the other built-in effects for jQuery. http://api.jquery.com/category/effects/
$(document).ready(function () {
$("#selectMenu").bind("change", function () {
if ($(this).val() == "pro1") {
$("#pro1").slideDown();
$("#pro2").slideUp();
}
else if($(this).val() =="pro2") {
$("#pro2").slideDown();
$("#pro1").slideUp();
}
});
});
HTML
<select id="selectMenu">
<option value="" >Please select product below</option>
<option value="pro1">Product 1</option>
<option value="pro2">Product 2</option>
</select>
My questions are How can I add the slideup/down script AND is there any other way to handle this?
Thank you!
My questions are How can I add the
slideup/down script AND is there any
other way to handle this?
If you make a convention that your <option/> value is the same as the id of the div you want to show, then you could alter your change event to look like this:
$("#selectMenu").bind("change", function() {
$(".hide").slideUp().filter("#" + $(this).val()).slideDown();
});
Example on jsfiddle.

Categories