Show/hide select values based on previous select choice - php

I have 2 select's inside a form. The second select has about 2000 lines in total coming out of my mysql table. One of the column into that mysql has 1 of the values used into the first select. I want to be able to filter on that value when it is selected into the first select, so that it only shows these articles.
code now:
<div class="rmaform">
<select name="discipline" class="discipline">
<option value=" " selected></option>
<option value="access">ACCESS</option>
<option value="inbraak">INBRAAK</option>
<option value="brand">BRAND</option>
<option value="cctv">CCTV</option>
<option value="airphone">AIRPHONE</option>
<option value="perimeter">PERIMETER</option>
</select>
</div>
<div class="rmaform">
<select name="article" class="input-article">
<?php
$articleselect = $dbh->prepare('SELECT * FROM articles');
$articleselect->execute();
while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
<?php
}
?>
</select>
I think i have to use Javascript for it but how do you combine PHP and Javascript? And what would be the best way to make the filter work?

jQuery for the change event and AJAX
$(document).ready(function(e) {
$('select.discipline').change(function(e) { // When the select is changed
var sel_value=$(this).val(); // Get the chosen value
$.ajax(
{
type: "POST",
url: "ajax.php", // The new PHP page which will get the option value, process it and return the possible options for second select
data: {selected_option: sel_value}, // Send the slected option to the PHP page
dataType:"HTML",
success: function(data)
{
$('select.input-article').append(data); // Append the possible values to the second select
}
});
});
});
In your AJAX.php
<?php
if(isset($_POST['selected_option']))
$selected_option=filter_input(INPUT_POST, "selected_option", FILTER_SANITIZE_STRING);
else exit(); // No value is sent
$query="SELECT * FROM articles WHERE discipline='$selected_option'"; // Just an example. Build the query as per your logic
// Process your query
$options="";
while($query->fetch()) // For simplicity. Proceed with your PDO
{
$options.="<option value='option_value'>Text for the Option</option>"; // Where option_value will be the value for you option and Text for the Option is the text displayed for the particular option
}
echo $options;
?>
Note: You can also use JSON instead of HTML for much simplicity. Read here, how to.

First give both of the selects an unique ids...
<div class="rmaform">
<select name="discipline" class="discipline" id="discipline">
<option value="" selected></option>
<option value="access">ACCESS</option>
<option value="inbraak">INBRAAK</option>
<option value="brand">BRAND</option>
<option value="cctv">CCTV</option>
<option value="airphone">AIRPHONE</option>
<option value="perimeter">PERIMETER</option>
</select>
</div>
<div class="rmaform">
<select name="article" class="input-article" id="article">
<option value="" selected></option>
</select>
Now you can use jQuery Ajax call to another file and get the HTML Response from that file and Populate in the select field with id="article" like this...
<script type="text/javascript">
$(document).ready(function(){
$("#discipline").change(function(){
var discipline = $(this).val();
$.post(
"ajax_load_articles.php",
{discipline : discipline},
function(data){
$("#article").html(data);
}
)
});
});
</script>
Now create a new file like ajax_load_articles.php... in the same directory where the html file exists... You can place it anywhere but then you have to change the $.post("url", the url to the ajax submission.
Contents of ajax_load_articles.php :
<?php
$discipline = $_POST["discipline"];
$articleselect = $dbh->prepare("SELECT * FROM articles WHERE colname = '{$discipline}'");
$articleselect->execute();
echo '<option value="" selected></option>';
while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
<?php
}
?>
Now when ever you will change the select of the first select field an Ajax call will take place and the data of the second select field will automatically adjust to related data selected in the first select field.

This is an example where you can select the college specific to the state ..
Form.php
// your code for form ...
// select box for state starts
<div class="form-group">
<label for="select" class="col-lg-2 col-md-2 control-label">State</label>
<div class="col-lg-10 col-md-10">
<select class="form-control input-sm" name="statename" id="stateid">
<option value="">---- Select ----</option>
<?php
$state=sql::readResultArray("Your Query To select State`");
foreach($state as $s){
?>
<option value="<?php echo $s?>"> <?php echo $s ?> </option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="select" class="col-lg-2 col-md-2 control-label">Colleges</label>
<div class="col-lg-10 col-md-10">
<select class="form-control input-sm" name="mycollegename">
<option value="">--- Select --- </option>
</select>
</div>
</div>
// further code for from in form.php..
Script to find the state and then pass the value to find the respective colleges in that state
<script>
$(document).ready(function(e) {
$('#stateid').change(function()
{ ids=$('#stateid').val();
$.get('mycollege.php', {type:ids} ,function(msg){
$('select[name="mycollegename"]').html(msg);
});
});
});
</script>
Call this file through ajax .. Code on this file
mycollege.php
<?php
require('db.php'); // call all function required, db files or any crud files
$type=$_GET['type'];
if(!empty($type)){
$r=sql::read("Your Query To call all teh college list");
?>
<select name="mycollegename">
<option value="">Select One</option>
<?php
foreach($r as $r){
echo "<option value=\"$r->collegename\">$r->collegename </option>";
}
?>
</select>
<?php }else{ ?>
<select name="mycollegename">
<option value="">Select State</option>
</select>
<?php } ?>

Related

Showing content in select box base on previous select box

hello developer community.I need your help.i am building a project on attendance management.In this project,i got stucked on one feature.
what i want is to display the departments based on the block input without going to next page.
<div class="form-group">
<label for="block" class="control-label col-sm-2">Select block:</label>
<div class="col-xs-10">
<select class="form-control" name="block" id="block">
<option selected="selected" value="">Select Block:</option>
<?php
$q="select * from blocks ORDER BY block_name";
$res=mysqli_query($con,$q);
while($row=mysqli_fetch_array($res)){
echo "<option value='$row[block_id]'class='form-control'>".$row['block_name']."</option>";
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="department" class="control-label col-sm-2">Select department:</label>
<div class="col-xs-10">
<select class="form-control" name="department" id="department">
<option selected="selected" value="">Select Department:</option>
<?php
$q="select * from departments ORDER BY department_name";
$res=mysqli_query($con,$q);
while($row=mysqli_fetch_array($res)){
echo "<option value='$row[department_id]'class='form-control'>".$row['department_name']."</option>";
}
?>
</select>
</div>
Create a PHP file, e.g. dep-getter.php
<?php
// Include your connection config
include 'db-config.php';
// getting block value
$block = $_GET['block'];
$where = !empty($_GET['block']) ? "block='$block'" : '1=1';
$q="select * from departments ORDER BY department_name WHERE $where";
$res=mysqli_query($con,$q);
while($row=mysqli_fetch_array($res)){
echo "<option value='$row[department_id]'class='form-control'>".$row['department_name']."</option>";
}
?>
JavaScript/jQuery:
$(document).ready(function() {
$('.block-select').change(function() {
var val = $(this).val();
$.ajax({
url: '/path/to/dep-getter.php?block='+val,
method: 'GET',
success: function(data) {
$('.select-department').html(data);
},
error: function() {
console.log('Something went wrong!');
}
});
});
});
I use the before code for simple understanding. For detail explaination, you can read Ajax documentation.
Note:
You need adding class to Department select option with name select-department as a target to put ajax result.
Hope this help you.
The best way I think is using Ajax.
But if you don't know about Ajax yet, the idea is to reload the current page with appending query string with Block value, and then show the Department base on block value.
So, for getting block value and reloading you can use jQuery for simple way.
The code come like this.
The Block select option (adding class for selector):
<select class="block-select">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
JavaScript/jQuery:
$(document).ready(function() {
$('.block-select').change(function() {
var val = $(this).val();
var curUrl = window.location.href;
// Append the value to current URL & reload
var targetUrl = curUrl + '?block=' + val;
window.location.href = targetUrl;
});
});
And then change your Department select option to like this:
<select class="form-control" name="department" id="department">
<?php
$where = !empty($_GET['block']) ? "block='$_GET[block]'" : '1=1';
$q="select * from departments ORDER BY department_name WHERE $where";
$res=mysqli_query($con,$q);
while($row=mysqli_fetch_array($res)){
echo "<option value='$row[department_id]'class='form-control'>".$row['department_name']."</option>";
}
?>
</select>
The above code will checking for block value from URL, if the block not empty then we will get department data by block value, otherwise get all.

Dynamic generate form based on select box change value

I want to generate dynamic form based on select box change value.
Suppose i have a parent select box :
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
below select box is depend on first
<select name="select2" id="select2">
<option value="banana">Banana</option>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
</select>
Here is my 2 select boxes and i want 2 things
1) create dependency of 2 this select box
2 ) I want to generate a dynamic form based on change second select box value.
for example if i select apple then a form open with related apple value.
I am a new in jquery and i do not have any idea about it ( share me code script if any one knows)
You can follow this way to making a dynamic dropdown.
The following HTML code contains dependent dropdowns for countries and states. Country options are read from the database and shown in the dropdown on page load. Initially, the state dropdown has no options. On changing the country dropdown values, a jQuery function is called to get dependent state options and loaded dynamically.
<div class="frmDronpDown">
<div class="row">
<label>Country:</label><br/>
<select name="country" id="country-list" class="demoInputBox" onChange="getState(this.value);">
<option value="">Select Country</option>
<?php
foreach($results as $country) {
?>
<option value="<?php echo $country["id"]; ?>"><?php echo $country["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>State:</label><br/>
<select name="state" id="state-list" class="demoInputBox">
<option value="">Select State</option>
</select>
</div>
</div>
The following jQuery script shows a function to send an AJAX request to PHP to read state list depends on the selected country. This AJAX call is set with the selected country id.
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "get_state.php",
data:'country_id='+val,
success: function(data){
$("#state-list").html(data);
}
});
}
</script>
In PHP, it connects the database to retrieve “states” table values based on the country id passed by jQuery AJAX call. It forms state dropdown options and returns as the AJAX response. This response is inserted to the state dropdown.
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["country_id"])) {
$query ="SELECT * FROM states WHERE countryID = '" . $_POST["country_id"] . "'";
$results = $db_handle->runQuery($query);
?>
<option value="">Select State</option>
<?php
foreach($results as $state) {
?>
<option value="<?php echo $state["id"]; ?>"><?php echo $state["name"]; ?></option>
<?php
}
}
?>

Make certain criteria appear when selection is made?

User have some options, upon selecting one of them, I want to show more options which will depend on first selected option. Say, user has options to select the number of gates, like 1 or 2. Upon selecting a number I want to show options of all the gates lower than that number. That is,
if 1 is selected, show options of only gate 1.
if 2 is selected, show options of gate 2 and gate 1.
I have most of the variables within my phpmyadmin for storage purposes to avoid having to create alot of variables in the code. Just want some suggestions and if you see anything I can improve let me know.
<div class="form-div-element">
<label># of Gates</label>
<select class="gates-change" name="no_gate" required>
<option value="">Select Gate</option>
<option value="28">1 Gate</option>
<option value="29">2 Gates</option>
</select>
</div>
<?php
if($result)
{
foreach($result as $row)
{
if($row->id == 31 || $row->id == 32 || $row->id == 33)
{?>
<div class="form-div-element ecl-variation ecl-variation<?php echo $row->id;?>" style="display:block!important">
<?php }
else
{?>
<div class="form-div-element ecl-variation ecl-variation<?php echo $row->id;?>">
<?php }?>
<label><?php echo $row->variation_name;?></label>
<?php
if($row->variation_name == 'Stops')
{?>
<input type="hidden" name="stopvariationid" value="<?php echo $row->id;?>" id="stopvariationid"/>
<?php }
?>
<?php
$var_value = (explode("|",$row->variation_value));
$var_condition = $row->conditions;
$arr = array('height_convert_configuration');
//if($row->special_features != '')
//{
// check_special_function($var_value,$row->special_features,$var_condition);
//}
//else if($row->variation_type =='selectbox')
if($row->variation_type =='selectbox')
{
if($row->variation_function == 'calculation')
{?>
<select onchange = 'change_variation(this.value,<?php echo $row->id;?>)'>
<option value="">Select Option</option>
<?php for($i=0;$i<count($var_value);$i++)
{?>
<option value="<?php echo $var_value[$i];?>"><?php echo $var_value[$i];?></option>
<?php }?>
</select>
<?php }
else
{ ?>
<select class="gate_datatype" name="gate_type">
<option value="">Select Option</option>
<?php for($i=0;$i<count($var_value);$i++)
{?>
<option value="<?php echo $var_value[$i];?>|<?php echo $row->special_features;?>"><?php echo $var_value[$i];?></option>
<?php }?>
</select>
<?php }
}
else if($row->variation_type =='textbox')
{?>
<?php for($i=0;$i<count($var_value);$i++)
{?>
<?php echo $var_value[$i];?>
<?php }?>
<?php }
else if($row->variation_type =='radiobox')
{?>
<?php for($i=0;$i<count($var_value);$i++)
{?>
<div class="radiobox-cont">
<input onchange = 'change_radio_variation(this,this.value,<?php echo $row->id;?>)' type="radio" name="<?php echo $row->class;?>" value='<?php echo $var_value[$i];?>' /><?php echo $var_value[$i];?>
</div>
<?php }?>
<?php }
else if($row->variation_type =='checkbox')
{?>
<?php for($i=0;$i<count($var_value);$i++)
{?>
<div class="checkbox-cont <?php echo preg_replace('/\s+/', '_', $var_value1[$i]);?>">
<?php if('Cabin Telephone' == $var_value[$i])
{?>
<input checked type="checkbox" onchange="change_check_varitaion(this,this.value,<?php echo $row->id;?>)" name="other_option[]" value='<?php echo $var_value[$i];?>' disabled="disabled" /><?php echo $var_value[$i];?>
<?php }
else
{?>
<input type="checkbox" onchange="change_check_varitaion(this,this.value,<?php echo $row->id;?>)" name="other_option[]" value='<?php echo $var_value[$i];?>' /><?php echo $var_value[$i];?>
<?php }?>
</div>
<?php }?>
<?php }?>
</div>
<?php }
You can do this in two ways first way is to do ajax and second way is using css.
First method suppose this is your select code where you can select gate
<div class="form-div-element">
<label># of Gates</label>
<select id="gates" onchange="change()" class="gates-change" name="no_gate" required>
<option value="">Select Gate</option>
<option value="28">1 Gate</option>
<option value="29">2 Gates</option>
</select>
</div>
// and this is your sub gates options which will be empty at first and its display will be none
<div id="subgates_div" class="form-div-element" style="display:none;">
<label># of Sub Gates</label>
<select id="subgates" class="gates-change" name="sub_no_gate" required>
<option value="">Select Sub Gate</option>
</select>
</div>
on selecting gate what you can do is use ajax to get the sub options of the selected gate like this. in this code your url and my url will be different.
function change() {
var selected = $('#gates').find(":selected").attr("value");
$.ajax({
type: "POST",
url: '<?php echo base_url('get_sub_options') ?>',
dataType: 'json',
data: {category: selected},
success: function (data) {
console.log(data);
//remove disabled from province and change the options
$('#subgates_div').show();
$('select[name="sub_no_gate"]').html(data.subgates);
}
});
}
and your php function should be like this here first i have made an array named subgates. and i have retrieved subgates from database using the value from post. this query might be different in your case. the i have applied foreach loop for sub gates and created a new option element with respective subgate id and subgate name and appended it to array. and at last the array is returned using json_encode
function get_sub_category() {
$data['subgates'] = array();
$subgates = $this->db->get_where('subcategories', array('id' => $_POST['category']))->result();
foreach ($subgates as $key => $val) {
$data['subgates'][] = <<<EOD
<option value='$val->id'>$val->sub_gate_name</option>
EOD;
}
echo json_encode($data);
}
and the other method is using css. to do this you should list all this options of gate and subgates at first. like this
// gates options
<div class="form-div-element">
<label># of Gates</label>
<select id="gates" onchange="change()" class="gates-change" name="no_gate" required>
<option value="">Select Gate</option>
<option value="28">1 Gate</option>
<option value="29">2 Gates</option>
</select>
</div>
//sub gate options one
<div id="subgates-<?php echo $subgates->id; ?>" class="form-div-element" style="display:none;">
<label># of Sub Gates</label>
<select id="subgates" class="gates-change" name="sub_no_gate" required>
<option value="">Select Sub Gate</option>
</select>
</div>
//sub gate option 2
<div id="subgates-<?php echo $subgates->id; ?>" class="form-div-element" style="display:none;">
<label># of Sub Gates</label>
<select id="subgates" class="gates-change" name="sub_no_gate" required>
<option value="">Select Sub Gate</option>
</select>
</div>
// and so on
In this case what you should remember is that your sub gates option div id should be dynamic and display will be none at first
now when you select a gate use onchange and change the display css of respective sub gates like this
function change() {
$(".form-div-element").hide();
var selected = $('#gates').find(":selected").attr("value");
$('#subgates-'+selected).show();
}
hope this will give you some idea and if you have any confusion feel free to ask
All in all it seems to me that your question actually contains 2 questions:
How to dynamically show/hide DOM elements based on user selection
Upon selecting a number I want to show options of all the gates lower than that number.
How to optimize your PHP code
Just want some suggestions and if you see anything I can improve let me know.
Number two is way to broad! Maybe just one quick suggestion: If it works then its fine. Overlooked it fast and seems to be ok.
See my working snippet for number one, which actually only needs a little customization of your existing source code (if any at all). Don't forget its just a mockup; if you need some further help or want some deeper explanations about whats going on then let me know...
jQuery('.form-div-element').not('.ecl-variation').find('select').on('change', function() {
var i = -1,
$conditional = jQuery('.ecl-variation').hide(), // hide in advance
iGates = +(jQuery(this).find('option:selected').attr('data-gates-sum')); // get required gate(s) based on selected options "data-gates-sum"-attribute
// version based on text: `iGates = +($(this).find('option:selected').text().split(' ')[0])` | pro: no additional markup, con: error prone, maintenance
// count up to required gate(s) and make them visible
while ( ++i < iGates ) {
$conditional[i].style.display = 'block';
}
});
.ecl-variation{
display: none; /* hide conditional selects in advance */
}
<!-- minimized mockup -->
<div class="form-div-element">
<label># of Gates</label>
<select>
<option value="">Select Gate</option>
<!-- decided to add a data attribute instead of relying on text which could change more likely (maintenance) -->
<option value="28" data-gates-sum="1">1 Gate</option>
<option value="29" data-gates-sum="2">2 Gates</option>
</select>
</div>
<div class="form-div-element ecl-variation">
<label># of Gates | conditial 1</label>
<select>
<option value="">Select Gate Sub</option>
<option value="3">abc</option>
<option value="4">xyz</option>
</select>
</div>
<div class="form-div-element ecl-variation">
<label># of Gates | conditial 2</label>
<select>
<option value="">Select Gate Sub</option>
<option value="5">123</option>
<option value="6">789</option>
</select>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
How to implement?
.ecl-variation{
display: none; /* hide conditional selects in advance */
}
<body>
<!-- minimized mockup -->
<div class="form-div-element">
<label># of Gates</label>
<select>
<option value="">Select Gate</option>
<option value="28" data-gates-sum="1">1 Gate</option>
<option value="29" data-gates-sum="2">2 Gates</option>
</select>
</div>
<div class="form-div-element ecl-variation">
<label># of Gates | conditial 1</label>
<select>
<option value="">Select Gate Sub</option>
<option value="3">abc</option>
<option value="4">xyz</option>
</select>
</div>
<div class="form-div-element ecl-variation">
<label># of Gates | conditial 2</label>
<select>
<option value="">Select Gate Sub</option>
<option value="5">123</option>
<option value="6">789</option>
</select>
</div>
<!-- YOUR CODE ENDS HERE -->
<!-- load jquery from cdn -->
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<!-- provide a local copy as fallback in case that cdn is not available -->
<script>window.jQuery||document.write('<script src="path/to/your/local/copy/jquery-1.12.4.min.js"><\/script>')</script>
<!-- implement your custom site specific script(s) inline -->
<script>
(function( $ ) {
$('.form-div-element').not('.ecl-variation').find('select').on('change', function() {
var i = -1,
$conditional = $('.ecl-variation').hide(),
iGates = +($(this).find('option:selected').attr('data-gates-sum'));
while ( ++i < iGates ) {
$conditional[i].style.display = 'block';
}
});
})( jQuery )
</script>
<!-- instead of deploying your scripts inline you can load them also like this:
<script src="path/to/your/app.js"></script>
-->
</body><!-- make sure that your scripts are located just before the closing body tag -->

How do I selectively add 3rd select box or relabel & redirect to a 2nd select box?

I have a form where the 1st select box is required. Depending on the selection, a different table will be used as a source for the query to populate a 2nd select box. Then depending also on the 1st selection a 3rd select box may or may not be necessary. I have designed the form to initially show 3 select boxes, but the user would have to know to skip the 2nd select box in some cases. This is confusing at the least. As an example:
If None is selected for Company, then both the Cemetery & Section select boxes would have to shown (Section being dependent on Cemetery selected). If XYZ Company is selected, then only the Section select box would need to be seen / selected (as the Cemetery is Company specific):
<script>
function getCemetery(val) {
$.ajax({
type: "POST",
url: "get_cemetery.php",
data:'company_name='+val,
success: function(data){
$("#cemetery-list").html(data);
}
});
}
Here is the code of the form:
<body>
<div class="frmDronpDown">
<div class="row">
<label>Company:</label><br/>
<select name="company" id="company-list" class="demoInputBox" onChange="getCemetery(this.value);">
<option value="">Select Company</option>
<?php
foreach($results as $company) {
?>
<option value="<?php echo $company["name"]; ?>"><?php echo $company["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>Cemetery:</label><br/>
<select name="cemetery" id="cemetery-list" class="demoInputBox" onChange="getSection(this.value);">
<option value="">Select Cemetery</option>
<?php
foreach($results as $cemetery) {
?>
<option value="<?php echo $cemetery["name"]; ?>"><?php echo $cemetery["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>Section:</label><br/>
<select name="section" id="section-list" class="demoInputBox">
<option value="">Select Section</option>
</select>
</div>
</div>
</body>
And here is the additional php code the is called within the script:
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["company_name"])) {
if (($_POST["company_name"]<>"None") && ($_POST["company_name"]<>"Other")) {
$sql="SELECT name, available FROM compsections WHERE cname = '".$_POST["company_name"]."'"." ORDER by available desc;";
$result = mysql_query($sql) or die ( mysql_error());
$row = mysql_fetch_row($result);
$section = $row[0]; // best choice to use if auto fill
$query="SELECT * FROM compsections WHERE cname = '".$_POST["company_name"]."'"." ORDER by available desc;";
$results = $db_handle->runQuery($query);
echo '<option value="">Select Section</option>';
}else{
$query ="SELECT * FROM cemeteries";
$results = $db_handle->runQuery($query);
echo '<option value="">Select Cemetery</option>';
}
foreach($results as $cemetery) {
?>
<option value="<?php echo $cemetery["name"]; ?>"><?php echo $cemetery["name"]." - ".$cemetery["available"]; ?></option>
<?php
}
}
?>
Edit:
Thank you for telling me about .hide and .show. I have looked up examples and what I can find uses a button click. Would you show an example of using them in an php if..else?
Thank you in advance.
Russ
I used the following:
<script>
function wholesection() {
$( "#whole-section" ).slideUp( "fast", function() {
});
}
</script>
AND
echo '<script>',
'wholesection();',
'</script>'
;

Empty query result

in a web form there are two drop-down lists. The second list items should change dynamically depending on the value selected on the first drop-down list.
This is how am I trying to do it:
index.php:
...
<script>
function getClient(val) {
$.ajax({
type: "POST",
url: "get_contacts.php",
data:'client_id='+val,
success: function(data){
$("#contacts-list").html(data);
}
});
}
</script>
...
<div class="form-group">
<label for="mto_client" class="col-sm-2 control-label">MTO Client</label>
<div class="col-sm-10">
<select name="mto_client" id="clients_list" onChange="getClient(this.value)">
<option value="">Select a Client</option>
<?php
do {
?>
<option value="<?php echo $row_RSClients['id_client']?>" ><?php echo $row_RSClients['client_name']?></option>
<?php
} while ($row_RSClients = mysql_fetch_assoc($RSClients));
?>
</select>
</div>
</div>
<div class="form-group">
<label for="mto_client_contact" class="col-sm-2 control-label">MTO Client Contact</label>
<div class="col-sm-10">
<select name="state" id="contacts-list">
<option value="">Select Client Contact</option>
</select>
</div>
</div>
get_contacts.php
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["client_id"])) {
$query ="SELECT * FROM tb_client_contacts WHERE contact_client_id = '" . $_POST["client_id"] . "'";
$results = $db_handle->runQuery($query);
?>
<option value="">Select Client Contact</option>
<?php
foreach($results as $state) {
?>
<option value="<?php echo $state["id_client_contact"]; ?>"><?php echo $state["contact_name"]; ?></option>
<?php
}
}
?>
There are objects on the table tb_clients_contact that meet the condition, but the second drop-down list doesn't show any objects.
Any help is welcome.
Instead of
$("#contacts-list").html(data);
It should be
$('#contacts-list').empty().append(data);
empty() will clear first the options inside the contacts-list select field, then append() will insert the options from the result of your AJAX.
You can also look at the console log for errors. If you are using Google Chrome, hit F12 to display the console log.

Categories