Show subcategory for any chosen category - javascript

I've been looking for a way to automatically display a subcategory select drop-down, only if a user selects a category. If the user doesn't select a category, the subcategory dropdown will remain hidden.
I have been looking for a way to do it by referring to online tutorials and videos but all that I've tried so far does not really work.
So please, I will like to have an assistance on how I can solve this problem. I have created a database with 2 tables:
category: catId,catName and
subcategory: subcatId,catId,subcatName
and here is my html code
<div class="row required">
<label for="category_level_1">Category</label>
<div class="column">
<select id="Category" name="category" required="required" data-parsley-required-message="Please select a Category." data-level="0">
<option value="">Select Category</option>
<?php
$getCategory = $category->getAllCat();
if($getCategory){
while($result = $getCategory->fetch_assoc()){
?>
<option value="<?php echo $result['catId']; ?>"><?php echo $result['catName']; ?></option>
<?php
}
}
?>
</select>
</div>
</div>
<div id="Subcategory" class="row hidden" >
<label for="subcategory">Subcategory</label>
<div class="column">
<select id="Subcategory" name="subcategory" required="required" data-parsley-required-message="Please select a subcategory." data-level="1">
<option value="">Select sub-category</option>
</select>
</div>
</div>
Category Table
Subcategory Table
So any suggestions on how I can code it using php and javascript? I am totally new to php and javascript.

Try this code, I have found it while I need to implement dependable dropdown.(fiddle demo)
You can change design and logic as per your need.
Tip : Get category and subcategory in this format :
$cat = array(['t'] => array('t1', 't2', 't3'), ['x'] => array('x1', 'x2', 'x3'));
Controller:
$cat = $this->model_name->getCat();
$final = [];
foreach ($cat as $value) {
$final[$value['catName']][] = array('name' => $value['subcatName'], 'key' => $value['subcatId']);
}
Model: I have assumed category table name as cat and sub category as sub_cat, you can replace it with your table name.
function getCat() {
$this->db->select('*');
$this->db->from('cat a');
$this->db->join('sub_cat b', 'a.catId = b.catId');
$result = $this->db->get();
$cat = $result->result_array();
$final = [];
foreach ($cat as $value) {
$final[$value['catName']][] = array('name' => $value['subcatName'], 'key' => $value['subcatId']);
}
}
View :
echo "<select class="dependent" name="products" multiple>";
foreach ($final as $catName => $sub) {
echo '<optgroup label="'.$catName.'">'.'<bR>';
foreach ($sub as $value) {
echo '<option value="'. $value['key'] .'">'. $value['name'] .'</option>';
}
}
echo "</select>";
You can loop through this and make dynamic dropdown.
jQuery Code :
$(function () {
$("select.dependent").each(function (i, sel) {
var original = $(this).clone(),
dependent = $("<select></select>").attr({
name: this.name
}).insertAfter(this)
this.name = "categories_" + this.name
$("optgroup", this).replaceWith(function () {
return "<option>" + this.label + "</option>"
})
$("option:first",this).prop("selected",true)
$(this).removeAttr("multiple").on("change", function () {
var cat = $(this).val()
dependent.html(original.children("[label='" + cat + "']").html())
}).change()
console.log(this)
})
})
HTML Code :
<select class="dependent" name="products" multiple>
<optgroup label="C1">
<option>P1A</option>
<option>P1B</option>
<option>P1C</option>
</optgroup>
<optgroup label="C2">
<option>P2A</option>
<option>P2B</option>
<option>P2C</option>
</optgroup>
<optgroup label="C3">
<option>P3A</option>
<option>P3B</option>
<option>P3C</option>
</optgroup>
</select>

Related

Set option values in a dropdown list based on the option from previous dropdown

So there are two drop-down lists in my code. One is "Specialization" which has options such as General, Cardiologist, Pediatrician, etc, and the other one is "Doctor" which has the name of the doctors as options. What I want is to show the names of the doctors in the "Doctor" drop-down based on the values selected in the "Specialization" drop-down.
This is how my JSON looks like:
[{"username":"Ashok","spec":"General"},{"username":"arun","spec":"Cardiologist"},{"username":"Dinesh","spec":"General"},{"username":"Ganesh","spec":"Pediatrician"},{"username":"Kumar","spec":"Pediatrician"},{"username":"Amit","spec":"Cardiologist"},{"username":"Abbis","spec":"Neurologist"}]
Eg: If I select 'General' from the "Specialization" drop-down, then only the doctors with General (Ashok and Dinesh) will be shown as the drop-down options in the "doctor" drop-down.
Here is the HTML and JS part:
<div class="col-md-4">
<label for="spec">Specialization:</label>
</div>
<div class="col-md-8">
<select name="spec" class="form-control" id="spec">
<option value="" disabled selected>Select Specialization</option>
<?php display_specs();?>
</select>
<script>
let data = <?php echo json_encode($docarray); ?>
document.getElementById('spec').onchange = function updateSpecs(e) {
let values = data.filter(obj => obj.spec == this.value).map(o => o.username);
document.getElementById('doctor1').value = document.querySelector(`[value=${//query that matches the doctor name in json}]`).getAttribute('data-value');
};
</script>
</div><br><br>
<div class="col-md-4"><label for="doctor">Doctors:</label></div>
<div class="col-md-8">
<select name="doctor" class="form-control" id="doctor1" required="required">
<option value="" disabled selected>Select Doctor</option>
<?php display_docs();?>
</select>
<script>
document.getElementById('doctor').onchange = function updateFees(e) {
document.getElementById('docFees').value = document.querySelector(`[value=${this.value}]`).getAttribute('data-value'); // fees will be added based on the doctor mentioned in the db
};
Here is the PHP code for 'display_specs()' and 'display docs()':
function display_docs()
{
global $con;
$query="select * from doctb";
$result=mysqli_query($con,$query);
while($row=mysqli_fetch_array($result))
{
$username=$row['username'];
$price=$row['docFees'];
echo '<option value="' .$username. '" data-value="'.$price.'">'.$username.'</option>';
}
}
function display_specs() {
global $con;
$query="select distinct(spec) from doctb";
$result=mysqli_query($con,$query);
while($row=mysqli_fetch_array($result))
{
$spec=$row['spec'];
$username=$row['username'];
echo '<option value="' .$username. '" data-value="'.$spec.'">'.$spec.'</option>';
}
}
Screenshot:
I did my best my couldn't able to do that. So any suggestions are welcome. Thanks in advance!
You can use additional attribute in docs list
data-spec="'.$spec.'"
function display_docs()
{
global $con;
$query = "select * from doctb";
$result = mysqli_query($con,$query);
while( $row = mysqli_fetch_array($result) )
{
$username = $row['username'];
$price = $row['docFees'];
$spec = $row['spec'];
echo '<option value="' .$username. '" data-value="'.$price.'" data-spec="'.$spec.'">'.$username.'</option>';
}
}
function display_specs() {
global $con;
$query = "select distinct(spec) from doctb";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{
$spec = $row['spec'];
$username = $row['username'];
echo '<option value = "' .$username. '" data-value = "'.$spec.'">'.$spec.'</option>';
}
}
then use JS to filter second select
document.getElementById('spec').onchange = function foo() {
let spec = this.value;
let docs = [...document.getElementById('doctor').options];
docs.forEach((el, ind, arr)=>{
arr[ind].setAttribute("style","");
if (el.getAttribute("data-spec") != spec ) {
arr[ind].setAttribute("style","display: none");
}
});
};
<div class="col-md-4">
<label for="spec">Specialization:</label>
</div>
<div class="col-md-8">
<select name="spec" class="form-control" id="spec">
<option value="" disabled selected>Select Specialization</option>
<option value="General">General</option>
<option value="Cardiologist">Cardiologist</option>
<option value="Pediatrician">Pediatrician</option>
<option value="Neurologist">Neurologist</option>
</select>
</div><br>
<div class="col-md-4"><label for="doctor">Doctors:</label></div>
<div class="col-md-8">
<select name="doctor" class="form-control" id="doctor" required="required">
<option value="" disabled selected>Select Doctor</option>
<option value="Ashok" data-spec="General">Ashok</option>
<option value="arun" data-spec="Cardiologist">arun</option>
<option value="Dinesh" data-spec="General">Dinesh</option>
<option value="Ganesh" data-spec="Pediatrician">Ganesh</option>
<option value="Kumar" data-spec="Pediatrician">Kumar</option>
<option value="Amit" data-spec="Cardiologist">Amit</option>
<option value="Abbis" data-spec="Neurologist">Abbis</option>
</select>
</div>

Dependent Drop Down select codeigniter Ajax

Im trying to get houses to be filled on the second dropdown from their respective estates selected in the first drop down. Im getting no results in the second dropdown.
This is the HTML:
<div class="col-sm-4 col-xs-12">
<div class="form-group drop-custum">
<select id="estate" name="estate" data-live-search="true" class="form-control show-tick"
onchange="get_houses(this.value)">
<option value="">-- Estate --</option>
<?php
$sql = $this->db->query("select * from estates ORDER BY estate_name asc");
$result = $sql->result();
foreach ($result as $estates):
?>
<option class="text-uppercase"
value="<?= $estates->estate_name?>"> <?= $estates->estate_name?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="col-sm-4 col-xs-12">
<div class="form-group drop-custum">
<select name="house" data-live-search="true" id="house"
class="form-control show-tick">
<option value="">-- House --</option>
</select>
</div>
</div>
This is the AJAX:
function get_houses()
{
$.ajax({
url:"fill_houses/",
type:"POST",
data:'estate_name='+val,
success:function(data)
{
$("#house").html(data);
alert('success');
}
});
}
This is the PHP:
public function fill_houses()
{
$query = "select * from houses where estate_name='" . $_POST["estate_name"] . "' order by house_number asc ";
$result = $query->result();
foreach ($result as $estates):
'<option class="text-uppercase" value="'.$estates->house_id.'"> '.$estates->house_number.'</option>';
endforeach;
}
You must return the value back in php function fill_houses().
public function fill_houses()
{
$query = $this->db->query("select * from houses where estate_name='" . $_POST["estate_name"] . "' order by house_number asc ");
$result = $query->result();
foreach ($result as $estates):
return '<option class="text-uppercase" value="'.$estates->house_id.'"> '.$estates->house_number.'</option>';
endforeach;
}
also in javascript ajax function get_houses() you need to get the variable. and a couple of edit.
function get_houses(val)
{
$.ajax({
url:"fill_houses/",
type:"POST",
data: { 'estate_name': val} ,
success:function(data)
{
$("#house").html(data);
alert('success');
}
});
}

Populate Dropdown based on another Dropdown Using Ajax, jQuery and Codeigniter on Update

I have created a dropdown that populates another dropdown.
I have created a modal for update in my application and I want the selected value of the dropdown to be the name taken from the database. It shows the name, but the problem is it doesnt show the other names which should be included.
(Note that the names show up depending on the first dropdown)
Here is my Model
function get_agents($campaign_id)
{
$campaign_id1 = mysqli_real_escape_string($this->db->conn_id,trim($campaign_id));
$query = $this->db->query("SELECT tbl_employee.emp_id, CONCAT(tbl_applicant.fname, ' ', tbl_applicant.lname) AS fullname FROM tbl_applicant INNER JOIN tbl_employee ON tbl_employee.apid=tbl_applicant.apid INNER JOIN tbl_account ON tbl_employee.acc_id=tbl_account.acc_id WHERE tbl_account.acc_id='".$campaign_id1."' ORDER BY tbl_applicant.fname ASC");
return $query->result();
}
Here is my Controller
public function getAgents()
{
$campaign_id = $this->input->post('campaign_id');
$data = $this->KudosModel->get_agents($campaign_id);
echo "<option value=''>-- Select Ambassador Name --</option>";
foreach($data as $a)
{
echo "<option value='".$a->emp_id."'>".$a->fullname."</option>";
}
}
Here is my View
<div class="form-group" style="height: auto; overflow: auto;">
<label class="col-sm-3 control-label float-left">Ambassador Name</label>
<div class="col-sm-9">
<select class="form-control" id="agentNames<?php echo $val->kudos_id; ?>" required="true" data-trigger="change" value="<?php echo $val->ambassador; ?>">
<option selected="" value="">-- Select Ambassador Name --</option>
<option selected="selected" value=""><?php echo $val->ambassador;?></option>
<?php
foreach($name2 as $row)
{
if($val->campaign==$row->acc_name)
echo '<'; if($val->ambassador==$row->fullname){
echo 'selected=selected';
}echo'option value="'.$row->emp_id.'">'.$row->fullname.'</option>';
}
?>
</select>
</div>
Here is my JQuery
$('#addCampaign<?php echo $val->kudos_id; ?>').on('change', function(){
$.ajax({
type : 'POST',
data : 'campaign_id='+ $('#addCampaign<?php echo $val->kudos_id; ?>').val(),
url : "<?php echo base_url(); ?>index.php/Kudos/getAgents/",
success : function(data){
//data returns your name, iterate through it and add the name to another select
$('#agentNames<?php echo $val->kudos_id; ?>').html(data);
}
});
});

Not Getting Updated Selected Value from a Dynamically made DropDown

I'm not getting value from a City-list DropDown which is Dynamically made. I'm first making required data Jason using AJAX in a Script and then sending it to another page to create Dynamic DropDown. In this City-list is my dynamic made dropdown which depends on the selection of Provincedown Dropdown but the problem comes when I select any option from City-list dropdown which is Dynamically build using ajax than its very first value comes as a selection no matter what option you have selected. Any Suggestions.Here is my Code of provincedown and City-list Dropdown.
<input type="hidden" name="City_Name" value="<?= $City_Name; ?>" >
<input type="hidden" name="Province_Name" value="<?= $ProvinceName ?>" >
<label>Province: </label><br>
<select name="Provincedown" id="ProvinceDropDown" class="form-control" onChange="getState(this.value);">
<option value="SelectProvince" <?=$ProvinceName == 'SelectProvince' ? ' selected="selected"' : '';?> > Please Select </option>
<option value="Sindh" <?=$ProvinceName == 'Sindh' ? ' selected="selected"' : '';?>> Sindh </option>
</select>
<label>City:</label><br/>
<select name="City-list" id="City-list" >
<option value="SelectCity" >Select City</option>
</select>
making data jason using AJAX whom code is
<body onload="getState()">
<script>
function getState(val) {
//var cityName = $City_Name;
var City_Name = $("input[name='City_Name']").val();
var Province_id = $("input[name='Province_Name']").val();
$.ajax({
type: "POST",
url: "fetch_state_Edit.php",
data:{country_id : val, City_Name : City_Name,Province_id : Province_id},
success: function(data){
$("#City-list").html(data);
}
});
}
</script>
fetch_state_Edit.php
<?php
if(!empty($_POST["Province_id"])) {
$country_id =$_POST['country_id'];
if($country_id=="SelectProvince" || $country_id=="")
$country_id=$_POST['Province_id'];
$City_Name=$_POST['City_Name'];
$results = mysqli_query($con, "SELECT City_Name FROM location WHERE Province = '$country_id' ");
?>
<option value="SelectCity">Select City</option>
<?php
foreach($results as $state) {
?>
<option value="<?php $state["City_Name"]; ?>" <?=$state["City_Name"] == $City_Name ? ' selected="selected"' : '';?>><?php echo $state["City_Name"];</option>
<?php
}
}
?>
Problem is in fetch_state_Edit.php file Just put echo before $state["City_Name"];
<?php
if(!empty($_POST["Province_id"])) {
$country_id =$_POST['country_id'];
if($country_id=="SelectProvince" || $country_id=="")
$country_id=$_POST['Province_id'];
$City_Name=$_POST['City_Name'];
$results = mysqli_query($con, "SELECT City_Name FROM location WHERE Province = '$country_id' ");
?>
<option value="SelectCity">Select City</option>
<?php
foreach($results as $state) {
?>
<option value="<?php echo $state["City_Name"]; ?>" <?=$state["City_Name"] == $City_Name ? ' selected="selected"' : '';?>><?php echo $state["City_Name"]; </option>
<?php
}
}
?>

PHP - Fetch value based on what is selected from option

<select class="selectpicker" name="mscr_type" id="mscr_type">
<?php $fpp_type = '';
foreach ($getmilestone_cr as $mscr_list) {
$description = $mscr_list['FIX_PRJ_DESC'];//fetch description
if ($fpp_type != $mscr_list['FIX_PRJ_TYPE']) {
if ($fpp_type != '') {
echo '</optgroup>';
}
if($mscr_list['FIX_PRJ_TYPE'] == 'MS'):
echo $fpp_label = "Milestone";
elseif($mscr_list['FIX_PRJ_TYPE'] == 'CR'):
echo $fpp_label = "Change Request(CR)";
endif;
echo '<optgroup label="'.$fpp_label.'">';
}
echo '<option value="'.$mscr_list['FIX_PRJ_TYPE'].'">'.htmlspecialchars($mscr_list['FIX_PRJ_NAME']).'</option>';
$fpp_type = $mscr_list['FIX_PRJ_TYPE'];
}
if ($fpp_type != '') {
echo '</optgroup>';
}
?>
</select>
The above code outputs:
<select class="selectpicker">
<optgroup label="Picnic">
<option value ="1">Mustard</option>
<option value ="2">Ketchup</option>
<option value ="3">Relish</option>
</optgroup>
<optgroup label="Camping">
<option value ="4">Tent</option>
<option value ="5">Flashlight</option>
<option value ="6">Toilet Paper</option>
</optgroup>
</select>
How could I fetch description based on what is selected from selected option. For example if Mustard is selected, then input value should be filled
with value 'Mustard is yellow in color'.
Tried using <select class="selectpicker" name="mscr_type" id="mscr_type" onchange="document.getElementById('mscr_description').value=this.options[this.selectedIndex].text"> but it fetches the name and not description.
<label for="name" class="label">Description</label>
<input type="text" disabled="" id="selectpicker_description" name="selectpicker_description" class="span3">
Add the description to the HTML using a data-XXX attribute:
echo '<option value="'.$mscr_list['FIX_PRJ_TYPE'].'" data-description="'.htmlspecialchars($description).'">'.htmlspecialchars($mscr_list['FIX_PRJ_NAME']).'</option>';
Then you can use
onchange="updateDescription(this)"
with the Javascript function:
function updateDescription(sel) {
var output = document.getElementById('mscr_description');
var desc = sel.options[sel.selectedIndex].getAttribute('data-description');
output.value = desc;
}

Categories

Resources