Populate dropdown list from another dropdown list - javascript

I'm trying to populate a select menu based on the value selected on another select menu.
So far, I managed to get the value and my PHP code does return the values as JSON. However, I can't seem to figure out how to show the data in the next select menu.
<div class="form-group">
<label for="laptopBrand">Laptop Brand</label>
<select class="form-control" id="laptopBrand">
<?php foreach($laptop_brands as $laptop_brand): ?>
<option value="<?= $laptop_brand['Lbrand'] ?>"><?= $laptop_brand['Lbrand'] ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="laptopSeries">Laptop Series</label>
<select class="form-control" id="laptopSeries">
</select>
</div>
JQuery
$("#laptopBrand").change(function(){
var lbrand = $(this).val();
$.ajax({
type: "POST",
data: 'laptopSeries='+lbrand,
url: 'includes/fetch.php',
dataType: 'json',
success: function(json) {
var a = JSON.parse(json);
alert(a);
var $el = $("#laptopSeries");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
$.each(json, function(value, key) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
}
});
});
PHP
if($_POST){
$laptopSeries = $_POST['laptopSeries'];
try{
$stmt = $db_con->prepare("SELECT `Lseries` FROM `laptop` WHERE `Lbrand` = '$laptopSeries'");
$stmt->execute();
$series = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($series as $series) {
$array = array($series['Lseries'] => $series['Lseries']);
echo json_encode($array);
}
}catch(PDOException $e){
echo $e->getMessage();
}
}

Do like this and make sure your server code return exactly what you want to fill in key and value.
$.each(a,function(key, value) // a or jsondata
{
$select.append('<option value=' + key + '>' + value + '</option>');
});

Related

Append data working after trigger at third time?

I want to make a dynamic dropdown using selectpicker bootstrap library, codeigniter 4, and AJAX.
I got a problem when I trigger to select the first dropdown, the second dropdown's option appended at third times select. Here I provide the video :
https://youtu.be/AVUBlhajZ_k
Here is my code:
MODEL :
function barangBySupp($namaSupp)
{
$supp = $namaSupp;
$data = $this->db->query("SELECT * FROM tablebarang WHERE supplier='$supp'");
$result = $data->getResultObject();
return $result;
}
CONTROLLER :
public function post()
{
$request = service('request');
if ($request->isAJAX()) {
$namaSupp = $request->getVar('id');
$data = $this->barangMasukModel->barangBySupp($namaSupp);
echo json_encode($data);
}
}
JAVASCRIPT
$("#selectOptSupp").on('changed.bs.select', function(e, clickedIndex, isSelected, previousValue){
const id = $('#selectOptSupp option:selected').data('nama');
const alamat = $('#selectOptSupp option:selected').data('alamat');
const noTelp = $('#selectOptSupp option:selected').data('notelp');
$('[name=namaSupp]').val(id);
$('[name=alamatSupp]').val(alamat);
$('[name=noTelp]').val(noTelp);
$.ajax({
type: "post",
url: "/BarangMasuk/post",
dataType: "JSON",
data: {
id: id
},
cache: false,
success: function(response) {
$.each(response, function(index, data){
$('#selBarang').append('<option data-nama="'+data['namaBarang']+'" data-harga="'+data['harga']+'" data-unit="'+data['unit']+'" value="'+data['namaBarang']+'" data-tokens="'+data['namaBarang']+'">'+data['namaBarang']+'</option>').selectpicker("refresh");
});
SHORT VIEW CODE :
<select id="selectOptSupp" class="form-control selectpicker" data-live-search="true">
<?php foreach ($supplier as $value) : ?>
<option data-nama="<?= $value['namaSupp']; ?>" data-notelp="<?= $value['noTelpSupp']; ?>" data-alamat="<?= $value['alamatSupp']; ?>" data-tokens="<?= $value['namaSupp'] ?>" name="" value="<?= $value['namaSupp'] ?>"><?= $value['namaSupp'] ?>
</option>
<?php endforeach; ?>
</select>
<select id="selBarang" class="form-control selectpicker" data-live-search="true">
// OPTION DATA SHOULD APPEND HERE WHEN #selectOptSupp fires
</select>

Dynamically load second bootstrap selectpicker based on user input of first selectpicker in codeigniter

I want to load data from the database to the second selectpicker based on the input id of the first selectpicker. In the database id of the first selectpicker is the foreign key of the second selectpicker.
View file
1st selectpicker
<select name="depot_select" id="depot_select" class="selectpicker" data-live-search="true" value="<?php echo set_value('depot_select');?>">
<option value="">No Depot Selected</option>
<?php echo $depots['depot'] ?>
</select>
2nd selectpicker
<select class="selectpicker" data-live-search="true" name="route_select" id="route_select" value="<?php echo set_value('route_select');?>">
<option value="">No Route Selected</option>
<?php echo $routes['route']?>
</select>
Ajax
function fetchDepot(){
$.ajax({
type :'POST',
url : '<?php echo base_url('transporter_dashboard/bus/get_depots'); ?>',
dataType: 'json',
success : function(data)
{
$('#depot_select').empty();
var example = $('#depot_select').selectpicker('val', data['data']);
console.log("depot_select" + example);
if(!$.isEmptyObject(data))
{
$.each(data, function(i,o)
{
var depot = $('#depot_select').append('<option value="'+ o['dpt_id'] +'">'+o['dpt_name'] +' </option>');
});
}
$('#depot_select').selectpicker('refresh');
fetchRoute();
},
error: function()
{
alert('error occour..........!');
}
});
}
function fetchRoute()
{
$.ajax(
{
type :'POST',
url :'<?php echo base_url('transporter_dashboard/bus/get_routes'); ?>',
data : { dpt_id : $('#depot_select option:selected').val()},
dataType: 'json',
success : function(data)
{
$('#route_select').empty();
$('#route_select').selectpicker('val', data['data']);
if(!$.isEmptyObject(data))
{
$.each(data, function(i,o)
{
var route = $('#route_select').append('<option value="'+ o['rot_id'] +'">'+ o['rot_name'] +'</option>');
});
}
$('#route_select').selectpicker('refresh');
},
error: function(data){
alert('error occour..........!');
}
});
}
Controller
function get_depots()
{
echo json_encode($this->bus_model->get_depots());
}
function get_routes()
{
if ($this->input->post('dpt_id'))
{
echo json_encode($this->bus_model->get_routes($this->input->post('dpt_id')));
}
}
Model
function get_depots()
{
$this->db->select('*');
$data = $this->db->get('depots')->result_array();
return $data;
}
function get_routes($id)
{
$data = array();
$this->db->select('*');
$this->db->where('dpt_id',$id);
$data = $this->db->get('routes')->result_array();
return $data;
}
According to the above code, only the id of the first option goes to the backend every time despite what option is selected. Then database load only those data which belongs to the id of the first option.
Finally, I found the answer to this question. We need to call fetchRoute() function inside of the $( document ).ready()

Dynamic drop down using single table in codeIgniter

Table
Here when I select Category 1 from drop down I should get district names which comes under Category 1 and for Category 2 I should get districts of Category 2 and so on....
As of now in my code i'm pulling out all district names from my district table master by using district codes. But I should get district names based on category selection.
View:
<select class="form-control" name="category" id='cat_id'>
<?php
foreach($query1 as $row)
{
echo '<option value="'.$row->category.'">'.$row->category.'</option>';
}
?>
</select>
<select name="placename" id="placename">
<?php
foreach($query2 as $row)
{
echo '<option value="'.$row->district_name.'">'.$row-
>district_name.'</option>';
}
?>
</select>
Model:
function viewcatplace()
{
$this->db->select("district.district_name");
$this->db->from('district');
$this->db->join('jc_place_master', 'district.district_code =
jc_place_master.district');
$query = $this->db->get();
return $query->result();
}
Controller:
public function viewcatplace()
{
$this->load->model('JcMeetingExpense_model');
$data['query1'] = $this->JcMeetingExpense_model->viewcatprice();
$data['query2'] = $this->JcMeetingExpense_model->viewcatplace();
$this->load->view('JcMeetingExpense/place_view',$data);
}
You can use this demo for your solution : https://www.codexworld.com/dynamic-dependent-dropdown-codeigniter-jquery-ajax/
It can be only done by ajax:
In controller:
public function index()
{
$web = array();
$web['title'] = 'Select tool';
$web['content'] = 'web/category_index';
// $web['data'] = $this->Common_model->get_all('category','*','','');
$web['data'] = $this->db->query('SELECT DISTINCT category FROM category')->result();
$this->load->view('web_template', $web);
}
Load the category data in select option:
<select class="form-control" id="select_category">
<option value="" disabled selected>Select category</option>
<?php if (isset($data) && !empty($data)) : ?>
<?php foreach ($data as $key => $value) : ?>
<option value="<?php echo $value->category; ?>"><?php echo $value->category; ?></option>
<?php endforeach; ?>
<?php endif; ?>
</select>
<select class="form-control" id="append_district"></select>
Using jquery change event get the data using ajax call:
<script type="text/javascript">
$(document).on('change',"#select_category",function (e) {
var optVal= $("#select_category option:selected").val();
if (optVal) {
$.ajax({
type: "post",
url: "getCategoryDetails",
cache: false,
data: {'category' : optVal},
success: function(json){
try {
var obj = jQuery.parseJSON(json);
$('#append_district').empty();
var append_data = '';
if (obj.length > 0) {
$.each(obj, function( index, value ) {
append_data += '<option value="'+value.district+'">'+value.district+'</option>'
});
$('#append_district').append(append_data);
}
} catch(e) {
console.log('Exception while request..');
}
},
error: function(){
console.log('Error while request..');
}
});
}
});
</script>
The data can be get by JSON format.In controller add this method:
public function getCategoryDetails() {
$category = $_POST['category'];
$categoryData = $this->db->query('SELECT district FROM category where category="'.$category.'"')->result();
echo json_encode ($categoryData) ;
}

getting select box to display selected value in different select box

I have two select boxes in which I want to select a value for one and the second select box should get same value.
Currently I am passing id and want my designation also to pass to ajax. Can I know how this can be implemented via ajax. Any help will be highly appreciated.
<select name="designation" class="form-control" id="desig" >
<option value="">Select a Designation/Role</option>
<?php
$sql = mysql_query("SELECT id, designation FROM tbl where status =1 and designationtype_id = 1 ");
while ($rows = mysql_fetch_assoc($sql)){
echo "<option value=" . $rows['id'] . ">" . $rows['designation'] . "</option>";
}
?> <select name="dd" id="dd" class="form-control" disabled>
<option value=""></option>
</select>
My AJAX,
<script type="text/javascript">
$(document).ready(function() {
$("#desig").change(function() {
var id = $(this).val();
var dataString1 = 'id=' + id;
var des = $(this).val();
var dataString2 = 'designationname=' + des;
$.ajax({
type: "POST",
url: "escalation_ajax.php",
data: dataString,
cache: false,
success: function(html) {
var data = html.split(",");
$('#rephead').val(data[0]);
}
});
});
});
</script>
escalation_ajax.php
<?php
if ($_POST['id'])
{
if ($_POST['des'])
{
$des_id = $_POST['id'];
$designation = $_POST['des'];
$sql = mysql_query("SELECT designation_id, reporting_head FROM aafmindia_in_sbi.tbl_reporting_head WHERE status=1 and reporting_head_for='$des_id'");
if ($sql === FALSE)
{
trigger_error('Query failed returning error: ' . mysql_error() , E_USER_ERROR);
}
else
{
while ($row = mysql_fetch_array($sql))
{
$id = $row['designation_id'];
$reporting_head = $row['reporting_head'];
echo '<option value="' . $id . '">' . $reporting_head . '</option>' . ',' . '<option value="' . $des_id . '">' . $designation . '</option>';
}
}
}
}
?>
What you could do, is have the second select (the one that needs the same value as the first) in a seperate file that you load via AJAX.
AJAX function:
function selection()
{
var selectValue=$("select#dd option:selected").val();
$.ajax({
type : "POST",
url : "escalation_ajax.php",
data : { id : selectValue },
success: function (html) {
$("#secondSelectorDiv").html(html);
}
})
}
What this does, is that when the selection() function is called, it will post the selected value of the first select to "escalation_ajax.php". It will then load that page into an element (div element in my example) with the id "secondSelectorDiv".
The html for the select with the function (which I will call onchange in this example), can look like this:
<select id="dd" onchange="selection();">
<option value=""></option>
</select>
<div id="secondSelectorDiv"></div>
Now in escalation_ajax.php you can retrieve the post variable and use it to look for the id in question for the second select.
<?php
$id=$_POST['id'];
/*
If you're using the id to fetch something in your database,
which it looks like you're doing, then use the post variable
to fetch your rows and build the select from that.
*/
$sql="SELECT * FROM table_name WHERE id='$id'";
$result_set=mysql_query($sql);
$row=mysql_fetch_array($result_set);
$count=mysql_num_rows(result_set);
$counter=0;
//this is the id you will check for in order to see what's to be selected
$idToCheck=$row['id'];
?>
<select id="dd2">
while($count > $counter)
{
counter++;
echo '<option value=""'; if($idToCheck == $id){ echo 'selected="selected"'; } echo '></option>';
}
?>
If you want the second select to be displayed before the first select has a value, you can simply just call an AJAX function that loads in the second select on page load.
IMPORTANT!: You should really switch to mysqli_* or PDO instead of using the deprecated mysql_*. You should at the very least look into sanitizing your inputs.

Need to append to select using JQuery

I need to append a HTML select option using jQuery. I have a piece of code that when a drop down is clicked, it fetches sub functions via AJAX. Once this is done, I also need to to add another option tag with a value of 99 and text of Other sub function. My code:
$.ajax({
type: "POST",
data: {function_id: function_id},
url: '<?php echo WEB_URL; ?>includes/ajax/target_audience_sub_functions.php',
dataType: 'json',
success: function(json) {
var $el = $("#target_audience_sub_function");
$el.empty(); // remove old options
$el.append($("<option></option>").attr("value", '').text('Please Select'));
$.each(json, function(value, key) {
$el.append($("<option></option>").attr("value", value).text(key));
});
$el.append($("<option></option>").attr("value", '99').text('Other sub function'));
}
});
The $el.append is the code I am trying to use to add the other option tag, but it doesn't work. I only get the ones from the AJAX. incidentally, the first append doesn't work either.
HTML
<div class="form-group">
<label for="target_audience_sub_function">Sub-Function</label>
<select data-selectedSubFunction="<?php echo (isset($audience)) ? $audience['target_audience_sub_function'] : ''; ?>" class="form-control light_grey_bg ta_sub_function" id="target_audience_sub_function" name="target_audience_sub_function[]">
<option value="">-- Choose sub function --</option>
<?php $get_functions = $db->get_all('sub_functions');
foreach ($get_functions as $function) { ?>
<option value="<?php echo $function['sub_function_id']; ?>" <?php echo isset($audience) ? $audience['target_audience_sub_function'] == $function['sub_function_id'] ? "selected='selected'" : "" : ''; ?> ><?php echo $function['sub_function_name']; ?></option>
<?php } ?>
</select>
</div>
Your code should work, I just tried it and the select got populated as you want it.
var json = {
0: 'Hello',
1: 'Bobby'
};
$(function() {
var $el = $("#target_audience_sub_function");
$el.click(function() {
$el.empty(); // remove old options
$el.append($("<option></option>").attr("value", '').text('Please Select'));
$.each(json, function(value, key) {
$el.append($("<option></option>").attr("value", value).text(key));
});
$el.append($("<option></option>").attr("value", '99').text('Other sub function'));
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="target_audience_sub_function"></select>
Maybe the success callback is never executed and the options you see are the one printed by PHP ?

Categories