I am using a stats app that will attach players (obtained from data within a database) to particular positions. I want players to disappear from being selected in forthcoming positions if they have already been selected so that the same player cannot be put in two separate positions. Can anyone suggest what to do here
This is the code, which i have summarised
<div class="row">
<div class="col-sm-4">
<label>1. Goalkeeper</label>
</div>
<div class="col-sm-4">
<select class="form-control">
<option value="" disabled selected>Select player</option>
<?php
include('conn.php');
$selectplayer= "SELECT * from panel";
$playerresult=$conn->query($selectplayer);
if(!$playerresult){
echo $conn->error;
}
while ($select=$playerresult->fetch_assoc()){
$identify=$select['id'];
$name=$select['name'];
echo "<option>$identify. $name</option>";
}
?>
</select>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<label>2. Right corner back</label>
</div>
<div class="col-sm-4">
<select class="form-control">
<option value="" disabled selected>Select player</option>
<?php
include('conn.php');
$selectplayer= "SELECT * from panel";
$playerresult=$conn->query($selectplayer);
if(!$playerresult){
echo $conn->error;
}
while ($select=$playerresult->fetch_assoc()){
$identify=$select['id'];
$name=$select['name'];
echo "<option>$identify. $name</option>";
}
?>
</select>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<label>3. Full back</label>
</div>
<div class="col-sm-4">
<select class="form-control">
<option value="" disabled selected>Select player</option>
<?php
include('conn.php');
$selectplayer= "SELECT * from panel";
$playerresult=$conn->query($selectplayer);
if(!$playerresult){
echo $conn->error;
}
while ($select=$playerresult->fetch_assoc()){
$identify=$select['id'];
$name=$select['name'];
echo "<option>$identify. $name</option>";
}
?>
</select>
</div>
</div>
Create a datalist with your players, and JQuery to remove from it when selected one using onchange() on the input:
function resetPlayerList(pos) {
//Get player name
var player = $('input#' + pos).val();
//If player exists in datalist
if($('option[value="' + player + '"]')) {
//Remove player from datalist meaning other inputs cannot add the player
$('option[value="' + player + '"]').remove();
}
//If changing a player, you need to add the old player back into the datalist. This code does not do that for you.
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<datalist id="players">
<option value="1">
<option value="2">
<option value="3">
<option value="4">
<option value="5">
<!-- etc. -->
</datalist>
<input id="CF" onchange="resetPlayerList('CF')" list="players"> <!-- Center Forward -->
<br/><br/>
<input id="LW" onchange="resetPlayerList('LW')" list="players"> <!-- Left Wing -->
This will remove the player from the list using JavaScript/JQuery.
If you want to change a player after adding them in, you will need to do more work, to first re-add the old set player back to the datalist, before removing the new player from it... does that make sense?
UPDATE
<datalist id="players">
<?php
$players = array(
array(
'name' => 'Player 1'
),
array(
'name' => 'Player 2'
)
);
//$players should be your array/object of players from SQL.
for($players as $player) {
echo '<option value="' . $player['name'] . '" />'; //or $player->name if object
}
?>
</datalist>
Related
I want to block the user to input I just want him to choose only from the list
I tried disable and readonly but this will disable my list and I don't want that.
This is my code
<div class="form-group row justify-content-center" id=" input-champs " style="margin-left:;" ><!-- grossistee -->
<label for="grossiste" class="col-2 col-form-label"></label>
<div class="col-3">
<input type="text" list="list-gro" placeholder="Grossiste1" id="g_name1" name="g_name1" class="form-control">
<datalist id="list-gro">
<?php while($row = mysqli_fetch_array($resultg)) { ?>
<option value="<?php echo $row['g_name']; ?>"><?php echo $row['g_name']; ?></option>
<?php } ?>
</datalist>
</div>
From the living standard spec of the datalist element:
Each option element that is a descendant of the datalist element, that is not disabled, and whose value is a string that isn't the empty string, represents a suggestion. Each suggestion has a value and a label.
Conversely, this means that a user can enter anything he wants. The datalist element only contains suggestions that the user can use, but does not have to.
For your puprose I 'd suggest a select element. A select element dictates strict values for the user to use.
<label for="my-select">My Select</label>
<select name="my-select" id="my-select" required>
<option value="" disabled selected>Select your option</option>
<?php foreach ($databaseresult as $row): ?>
<option value="<?= htmlspecialchars($row['value']) ?>">
<?= htmlspecialchars($row['label']) ?>
</option>
<?php endforeach ?>
</select>
Its better to use select in place of input as you dont want the user to type in anything from himself/herself.
You can do like this to implement select with database query
<select name="g_name1" id="g_name1" class="form-control">
<?php while($row = mysqli_fetch_array($resultg)) { ?>
<option value="<?php echo $row['g_name']; ?>"><?php echo $row['g_name']; ?></option>
<?php } ?>
</select>
In my application there is a form which have a two select field , in which the last select is set to have a multiple selection. What I need is to insert the first pair of select field to be inserted as a single record into the database. When I try to do this using a for loop I am able to insert the record as a single row until and unless I select only one value for my 2nd select field. But If I select multiple fields for second select, the records isn't proper.
Also here user can add more divs by clicking ADD button
<div id="scope-brand-div">
<div class="col-md-6">
<div class="form-group">
<label for="scope">Project Scope</label>
<select name="scope[]" class="form-control scope-select">
<option value=""></option>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="brands_used">Brands Used</label>
<select multiple name="brands_used[]" class="form-control brand-select">
<option value=""></option>
<option>D</option>
<option>E</option>
<option>F</option>
</select>
</div>
</div>
</div>
php
$s = $this->input->post('scope');
$b = $this->input->post('brands_used');
foreach( $s as $key => $n ) {
$rows[] = $n.",".$b[$key];
}
print_r($rows);
SCENARIO 1
If I select single fields for both select, the output will be:
A, D
B, E
SCENARIO 2
If I select a multiple filed for the second select like A,(D,E) and B,F. Using the same loop above the result will be:
A, D
B, E
How can I insert the same fields If I select multiple fields for 2nd select field ad provided the user can add more divs same like this.
Edit 1
<div id="scope-brand-div">
<div class="col-md-6">
<div class="form-group">
<label for="scope"><?php echo $this->lang->line('xin_project_scope');?></label>
<select name="scope[]" class="form-control select-border-color border-warning scope-select" data-plugin="select_hrm" data-placeholder="<?php echo $this->lang->line('xin_project_scope');?>">
<option value=""></option>
<?php foreach($all_project_scope as $scope) { ?>
<option value="<?php echo $scope->scope_name; ?>"><?php echo $scope->scope_name; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group brands-ajax">
<label for="brands_used"><?php echo $this->lang->line('xin_brands_used');?></label>
<select multiple name="brands_used[]" class="form-control select-border-color border-warning brand-select" data-plugin="select_hrm" data-placeholder="<?php echo $this->lang->line('xin_brands_used');?>">
<option value=""></option>
<?php foreach($all_brands as $brands) { ?>
<option value="<?php echo $brands->brand_name; ?>"><?php echo $brands->brand_name; ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#add-new').click(function(){
var invoice_items = '<div id="scope-brand-div">'
+ '<div class="col-md-6">'
+'<div class="form-group">'
+ '<label for="scope"><?php echo $this->lang->line('xin_project_scope');?></label>'
+'<select name="scope[]" class="form-control scope-select" data-placeholder="<?php echo $this->lang->line('xin_project_scope');?>">'
+'<option value=""></option>'
<?php foreach($all_project_scope as $scope) { ?>
+'<option value="<?php echo $scope->scope_name; ?>"><?php echo $scope->scope_name; ?></option>'
<?php } ?>
+ '</select>'
+ '</div>'
+ '</div>'
+ '<div class="col-md-6">'
+ '<div class="form-group brands-ajax">'
+ '<label for="brands_used"><?php echo $this->lang->line('xin_brands_used');?></label>'
+'<select name="brands_used[]" class="form-control brand-select" data-placeholder="<?php echo $this->lang->line('xin_brands_used');?>">'
+'<option value=""></option>'
<?php foreach($all_brands as $brands) { ?>
+'<option value="<?php echo $brands->brand_name; ?>"><?php echo $brands->brand_name; ?></option>'
<?php } ?>
+'</select>'
+'</div>'
+ '</div>'
+'</div>'
$('#clone-parent').append(invoice_items).fadeIn(500);
});
});
</script>
<?php
public function add_project() {
$s = $this->input->post('scope');
$b = $this->input->post('brands_used');
foreach( $s as $key => $n ) {
$rows[] = $n.",".$b[$key];
//insert query
}
}
?>
Edit 2
echo var_export($this->input->post('brands_used'));
array (
0 =>
array (
0 => 'Opterna',
),
1 =>
array (
0 => 'Norden',
),
2 => 'Opterna',
)
echo var_export($this->input->post('scope'));
array (
0 => 'ACS',
1 => 'SMA TV',
)
About your html...
the for in your label only works properly if associated with the id attribute of your field.
<option> tags which have identical values in the text and in the value attribute can have their value attribute removed entirely -- it works exactly the same at submission time but removes bloat from your html.
I am appending a counter to the id and the clonable class to your outermost <div> to aid the javascript cloning process.
brands_used[][] needs to be brands_used[0][] to prevent unwanted incrementation of the first level index.
Rewrite:
<div id="scope-brand-div0" class="clonable">
<div class="col-md-6">
<div class="form-group">
<label for="scope0"><?php echo $this->lang->line('xin_project_scope'); ?></label>
<select id="scope0" name="scope[]" class="form-control select-border-color border-warning scope-select" data-plugin="select_hrm" data-placeholder="<?php echo $this->lang->line('xin_project_scope'); ?>">
<option></option>
<?php foreach ($all_project_scope as $scope) {
echo "<option>{$scope->scope_name}</option>";
} ?>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group brands-ajax">
<label for="brands_used0"><?php echo $this->lang->line('xin_brands_used'); ?></label>
<select multiple id="brands_used0" name="brands_used[0][]" class="form-control select-border-color border-warning brand-select" data-plugin="select_hrm" data-placeholder="<?php echo $this->lang->line('xin_brands_used'); ?>">
<option></option>
<?php foreach ($all_brands as $brands) {
echo "<option>{$brands->brand_name}</option>";
} ?>
</select>
</div>
</div>
</div>
As for your cloning javascript... I advise that you use clone() to clean up your script. Perhaps draw some inspiration from https://stackoverflow.com/a/8018242/2943403.
You will need to ensure that a "counter" is implemented. The original/hardcoded set of fields will have 0 as the counter; all additional sets of fields should replace all 0 values with the next incremental integer. This will keep all related fields in their related groups at submission time.
Specifically:
<div id="scope-brand-div0"> (if you actually need it) will become <div id="scope-brand-div1">
<label for="scope0"> will become <label for="scope1">
<select id="scope0"> will become <select id="scope1">
<label for="brands_used0"> will become <label for="brands_used1">
<select multiple id="brands_used0" name="brands_used[0][]" will become <select multiple id="brands_used1" name="brands_used[1][]"
The, of course, if the Add button is clicked a second time, all of the 1's need to become 2's.
As for processing your $_POST data, I expect to receive a structure like this: (don't stop tweaking your form until it delivers this most-appropriate structure)
$_POST = [
'scope' => [
'ACS',
'SMA TV'
],
'brands_used' => [
[
'Opterna',
'Norden'
],
[
'Opterna'
]
]
];
This means you can use the same first level keys to access related scope and brands_used values. As you traverse the data, scope data will be a string and brands_used will be an array.
To iterate:
// make an object-oriented mysqli connection ($mysqli)
$stmt = $mysqli->prepare("INSERT INTO tablensme (scope, brand_used) VALUES (?, ?)");
$stmt->bind_param('ss', $scope, $brand_used);
$posted = $this->input->post();
foreach ($posted['scope'] as $index => $scope) {
// use $scope string
foreach ($posted['brands_used'][$index] as $brand_used) {
// use $brand_used string
$stmt->execute();
}
}
Assuming you have a normalized db table structure and want to write one scope value and one brand_used value per table row, set up your prepared statement and bound variables prior to the loop, then call execute() from the inner loop.
This is 100% NOT TESTED, but the intended result from inserting the sample data would be the following new rows:
('ACS', 'Opterna'),
('ACS', 'Norden'),
('SMA TV', 'Opterna')
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 -->
I have two drop downs .one have static value and second get values from db. I want to that if value is selected from 1st drop down then relevant values loaded in 2nd drop down. I have tried. but its load all the data from database according to user.for example when user select from request type dropdown having value inquiry.then 2nd drop down load only the values which have catType Inquiry.and if he select the complaint then complaint data must be shown.I have been tried but all the data is loaded ,or only one data is loading.any body help me in this regard.Thanks in Advance. Here is My Code
<div class="col-md-4">
<div class="form-group">
<label for="requesttype"><?php echo $requestField; ?></label>
<select class="form-control" required="" id="requesttype" name="requesttype" onchange="fcrActionChange(this);">
<option value="">Select Request Type</option>
<option value="Inquiry">Inquiry</option>
<option value="Complaint">Complaint</option>
<option value="Service Request/FCR">Service Request/FCR</option>
<option value="Verification Call">Verification Call</option>
</select>
<span class="help-block"><?php echo $requestHelp; ?></span>
</div>
</div>
$("#requesttype").change(function() {
$("#catId).load("navigation.php?requesttype=" + $("#requesttype").val());
});
</script>
<div class="col-md-4">
<div class="form-group">
<label for="catId"><?php echo $categoryField; ?></label>
<select class="form-control" name="catId" id="catId">
$tcat = "SELECT catId, catName FROM categories WHERE userId = ".$userId." AND isActive = 1 AND catType = ".$_GET['requesttype'];
$rest = mysqli_query($mysqli, $tcat) or die('-2'.mysqli_error());
while ($tcatrow = mysqli_fetch_assoc($rest)) {
echo "<option value="$tcatrow['catId'] >";
echo clean($tcatrow['catName'])."</option>";
}
</select>
<span class="help-block"><?php echo $categoryHelp; ?></span>
</div>
</div>
</div>
Your code is pretty confusing but anyway, the important part is within your ajax request and your PHP file
Ex. you have a div id secondOpt to be filled from the query made by the requesttype.
**Note I added a userId input field to pass the value for the SQL query in the navigation.php
<select class="form-control" required="" id="requesttype" name="requesttype" onchange="fcrActionChange(this);">
<option value="">Select Request Type</option>
<option value="Inquiry">Inquiry</option>
<option value="Complaint">Complaint</option>
<option value="Service Request/FCR">Service Request/FCR</option>
<option value="Verification Call">Verification Call</option>
</select>
<input type="hidden" id="userId" value="<?php echo $userId;?>">
<div id="secondOpt"></div>
After this, you will have an ajax request below, you can use $.post from jQuery and render the returned data on the secondOpt element
$('#requesttype').change(function(){
$.post("navigation.php",{requesttype: $(this).val(),userId: $('#userId').val()},function(options)
{
$('#secondOpt').html(options);
});
});
And for the navigation.php UPDATED
//don't forget your config file here to connect with the database
$userId = mysql_real_escape_string($_POST['userId']);
$requesttype = mysql_real_escape_string($_POST['requesttype']);
$output = "<select id='catId'>";
$tcat = "SELECT catId, catName FROM categories WHERE userId = ".$userId." AND isActive = 1 AND catType = ".$requesttype;
$rest = mysqli_query($mysqli, $tcat) or die('-2'.mysqli_error());
while ($tcatrow = mysqli_fetch_assoc($rest)) {
$output.="<option value=".$tcatrow['catId']." >";
$output.=clean($tcatrow['catName'])."</option>";
}
$output.="</select>";
echo $output;
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.