Issue re-hiding div class on reselect of original option jQuery - php

Can't seem to figure this out. Value does change as it is supposed to, but "#donateForm" doesn't hide upon selection of original option.
<select id="donateSelect">
<option value="0">Select</option>
<option value="General Fund">General Fund</option>
<?php
// display all project names as options
$prj_sql = "SELECT `name` FROM `tbl_projects`";
$prj_result = mysqli_query($database_link, $prj_sql);
while ($prj = mysqli_fetch_array($prj_result)) {
echo '<option value="'.$prj['name'].' Project Fund">'.$prj['name'].' Project Fund</option>';
}
?>
</select>
<div id="donateForm">
......
</div>
<script>
$('#donateForm').hide();
$('#donateSelect').on('change', function() {
if ($('#donateSelect').val() == "0") {
$('#donateForm').hide();
} else {
var donateValue = $(this).find('option:selected').attr('value');
$('#donateForm').show();
$('#item_name').val(donateValue);
}
});
</script>

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>

Dynamic Dependent Dropdown

I have a form that pulls some dropdown data from an existing db. I've been working on a second dropdown that references the first to get more specific information from a different DB, however it looks like my code is broken somewhere. The first dropdown is populated fine but when i choose a "Manager" the Site dropdown goes blank, I even lose the "Select Site" option.
Any help would be appreciated.
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
function getSite(val) {
$.ajax({
type: "POST",
url:"get_site.php",
data:'manager_id='+val,
success: function(data){
$("#site-list").html(data);
}
});
}
</script>
html/php
Manager<br/>
<select name="manager_id" onChange="getSite(this.value);">
<option value="">Select Manager</option>
<?php
$results = mysql_query("SELECT * FROM _managers");
while ($row_unit = mysql_fetch_array($results)){
?>
<option value="<?php echo $row_unit["id"]; ?>"><?php echo $row_unit["company"]; ?></option>
<?php
}
?>
</select>
<br/><br/>
Site<br/>
<select name="site_id" id="site-list">
<option value="">Select Site</option>
</select>
get_site.php
<?php
include('includes/connect-db.php');
if(!empty($_POST["manager_id"])) {
$manager_id = $_POST["manager_id"];
$results = mysql_query("SELECT * FROM _sites WHERE manager_id = $manager_id");
?>
<option value="">Select Site</option>
<?php
while ($row_site = mysql_fetch_array($results)){
?>
<option value="<?php echo $row_site["id"]; ?>"><?php echo $row_site["site_name"]; ?></option>
<?php
}
}
?>
As per discussion in comment.
I made the adjustment but still not getting my values from the
"get_site.php" file. Although now the "Select Site" stays in the site
dropdown.
Assuming you are getting proper data from MySQL server do some changes in get_site.php as below.
get_site.php
<?
include 'includes/connect-db.php';
if ((!empty($_POST["manager_id"])) && (isset($_POST["manager_id"])))
{
$manager_id = $_POST["manager_id"];
$results = mysql_query("SELECT * FROM _sites WHERE manager_id = '{$manager_id}'");
$options = "<option value=''>Select Site</option>";
while ($row_site = mysql_fetch_assoc($results))
{
$options .= "<option value='{$row_site['id']}''>{$row_site['site_name']}</option>";
}
return $options; // I personally prefer to echo using json_encode and decode it in jQuery
}
?>
Above code should give you the data you want.
Hope this solves your issue.Do comment if you are having any difficulties.

hide option select value based on option value selected on first options

I have two select option field.
<div style="float:left; width:7%">
<label>Type</label>
<select name="ostatus" id="ostatus" class="input-small">
<option value="Actual">Actual</option>
<option value="Ghost">Ghost</option>
</select>
<div style="float:left; width:7%">
<label>Upgrade</label>
<select name="oupg" id="oupg" class="input-small">
<option value="Exp" >Exp</option>
<option value="Post" >Post</option>
<option value="Upgrade" >Upg</option>
<option value="Retail" >Retail</option>
<option value="Prepaid" >Prepaid</option>
</select>
If on the Type select, Ghost is selected, I would like to hide option Retail and Prepaid under the upgrade options. How do I go about this? I am able to hide the whole div container for upgrade but I only want to hide those last two options. Please some assistance would be appreciated.
You can use jquery
$(document).ready(function(){
$('#ostatus').on('change',function() {
if($(this).val()== 'Ghost'){
$('#oupg') .find ("option[value=Retail]").hide();
$('#oupg') .find ("option[value=Prepaid]").hide();
}
else{
$('#oupg') .find ("option[value=Retail]").show();
$('#oupg') .find ("option[value=Prepaid]").show();
}
});
});
Using Javascript and display:none css styling you can accomplish this:
<head>
<script type="text/javascript">
function hideOpt() {
var type = document.getElementById("ostatus");
var upgrade = document.getElementById("oupg");
if (type.options[type.selectedIndex].value == 'Ghost') {
upgrade.options[3].style.display = 'none';
upgrade.options[4].style.display = 'none';
// IE exception
upgrade.options[3].disabled = true;
upgrade.options[4].disabled = true;
} else {
upgrade.options[3].style.display = 'block';
upgrade.options[4].style.display = 'block';
// IE exception
upgrade.options[3].disabled = false;
upgrade.options[4].disabled = false;
}
}
</script>
</head>
<label>Type</label>
<select name="ostatus" id="ostatus" onchange="return hideOpt();" class="input-small">
<option value="Actual">Actual</option>
<option value="Ghost">Ghost</option>
</select>
<label>Upgrade</label>
<select name="oupg" id="oupg" class="input-small">
<option value="Exp" >Exp</option>
<option value="Post" >Post</option>
<option value="Upgrade" >Upg</option>
<option value="Retail" >Retail</option>
<option value="Prepaid" >Prepaid</option>
</select>
Edit:
Added else statement to show the options again when 'Actual' is selected.
You can't hide option elements in all browsers, but you can disable them:
document.querySelector("#oupg option[value=Retail]").disabled = true;
document.querySelector("#oupg option[value=Prepaid]").disabled = true;
This will work in IE8 and up.
If you want IE7 and lower support, then:
var opts = document.getElementById("oupg").options;
opts[opts.length - 2].disabled = true;
opts[opts.length - 1].disabled = true;

PHP: Echo value of selected item from a dependable dropdown menu

I am currently working with a Dependable dropdown menu that functions with the help of jQuery and PHP. The values are being pulled of MySQL database. Is there away to php echo the selected value of a dependable drop down menu?
EXAMPLE
HTML/PHP
<form action="" method="post">
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="category" id="category" class="update"
disabled="disabled">
<option value="">----</option>
</select>
<select name="colour" id="colour" class="update"
disabled="disabled">
<option value="">----</option>
</select>
</form>
Please add jquery.js.
your html code
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="category" id="category" class="update" disabled="disabled">
<option value="">----</option>
</select>
<select name="colour" id="colour" class="update" disabled="disabled">
<option value="">----</option>
</select>
//jquery code for source list
<script type="text/javascript">
$(document).ready(function(){
$('#gender').change(function() {
if ($(this).val()!='') {
$("#category").load("postfile.php",{gender_id: $(this).val()});
$("#category").removeAttr('disabled');
}
});
//code on change of sel_source
$('#category').change(function() {
if ($(this).val()!='') {
$("#colour").load("postfile.php",{category_id: $(this).val()});
$("#colour").removeAttr('disabled');
}
});
});
</script>
//postfile.php
//your mysql connection other things goes here
//code for category
$objDb = new PDO('mysql:host=localhost;dbname=dbname', 'ur_username', 'ur_password');
if(isset($_REQUEST['gender_id']) && !empty($_REQUEST['gender_id'])) {
$sql = "SELECT * FROM `categories` WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($_REQUEST['gender_id']));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if(!empty($list)) {
$output = '<option value="">Select</option>';
foreach($list as $row) {
$output .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
} else {
$output = '<option value="">Select</option>';
}
echo $output;
}
//code for color
if(isset($_REQUEST['category_id']) && !empty($_REQUEST['category_id'])) {
$sql = "SELECT * FROM `categories` WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($_REQUEST['category_id']));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if(!empty($list)) {
$output = '<option value="">Select</option>';
foreach($list as $row) {
$output .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
} else {
$output = '<option value="">Select</option>';
}
echo $output;
}
Hope this will help you.
You are going to have to write a JavaScript function that retrieves the selected value or option from the first HTML select field. This function commonly writes out a new URL path to the current page with the addition of some concatonated Get Variables:
<script type="text/javascript">
getSelectedOptionValue() {
// create some variables to store your know values such as URL path and document
var myPath = " put the URL path to the current document here ";
var currentPage = "currentPage.php";
// get the values of any necessary select fields
var carMake = document.getElementById("carMake").value;
// write out the final URL with the Get Method variables you want using concatnitation
var getMethodURL = myPath + currentPage + "?carMake='" + carMake + "'";
// function refreshes page using the function made URL
window.location.replace( getMethodURL );
}
</script>
Since the second select field is dependent on the first you have to assume that the user is going to make a selection from the first choice of options. This means that the function that retrieves the value of the primary select field must run in response to a change in the fields selection. For example
<select name="carMake" id="carMake" onchange="getSelectedOptionValue();">
Depending on how you have set up your DB, you may want either the value of the option tag or the string presented to the user between the option tags...this is up to you keeping in mind how you may re-query the information if your original record set hasn't already pulled up the necessary info to write the second set of select option tags.
To write out the second select field using php simply repeat the while loop you have used for the first. This time replace your SQL statement with a new one using a variable in which you have stored the value retrieved from the new URL using the get method
<?php
// here I am using the more generic request method although you could use the get as well
$carMake = $_REQUEST['carMake'];
sql_secondSelectField = "SELECT * FROM tbl_carModels WHERE carMake = $carMake";
// Run new query and repeat similar while loop used to write your first select field ?>

Need chained select boxes to ALL appear before selecting values for the first select box

My chained select boxes currently work fine. The first select box is vehicle make or vmake, and the second box is vehicle model or vmodel. Right now, only the vmake select box appears when the page loads and the vmodel box only appears after you select a value for vmake. My client wants the vmodel and vmake select boxes to appear when the page loads (even though the vmodel box would be empty until the user makes a selection from vmake). It sounds silly, but the client really wants it this way.
Here is the jquery code from the main page
<script type="text/javascript">$(document).ready(function() {
$('#wait_1').hide();
$('#vmake').change(function(){
$('#wait_1').show();
$('#result_1').hide();
$.get("func.php", {
func: "vmake",
drop_var: $('#vmake').val()
}, function(response){
$('#result_1').fadeOut();
setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400);
});
return false;
});
});
function finishAjax(id, response) { $('#wait_1').hide(); $('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
</script>
This is the HTML that calls up the php page
<select name="vmake" id="vmake">
<option value="" selected="selected">Make</option>
<?php getTierOne(); ?>
</select>
<span id="wait_0">
</span>
<span id="result_1"></span>
This is the php script for getTierOne that calls up my database
function getTierOne(){$result = mysql_query("SELECT DISTINCT vmake FROM vmake")
or die(mysql_error());
while($tier = mysql_fetch_array( $result ))
{
echo '<option value="'.$tier['vmake'].'">'.$tier['vmake'].'</option>';
}}
And lastly this is the rest of the php
if($_GET['func'] == "vmake" && isset($_GET['func']))
{vmake($_GET['drop_var']);
}
function vmake($drop_var)
{
include_once('db.php');
$result = mysql_query("SELECT * FROM vmake WHERE vmake='$drop_var'")
or die(mysql_error());
echo '<select name="vmodel" id="vmodel" style="width:242">
<option style="width:242" value=" " selected="selected">Model</option>';
while($drop_2 = mysql_fetch_array( $result ))
{
echo '<option style="width:242" value="'.$drop_2['vmodel'].'">'.$drop_2['vmodel'].'</option>';
}
echo '</select> ';}
Im not sure what I need to change to get the vmodel box to appear when the page loads. Thanks for any suggestions, sorry for the long question.
A dropdown inside another dropdown? Is that posible?
<select name="vmake" id="vmake">
<option value="" selected="selected">Make</option>
<?php getTierOne(); ?> //this function will output
"<select name="vmake" id="vmake">
<option value="" selected="selected">Make</option>
</select>"
</select>

Categories