on change not working in nested dropdown list - php

hello i want to display data of business3's data according to business2's and business2's data according to business1's dropdown list but on change() of business1 i got data in response but I didn't get second on change() in dropdown list.
<!-- ajax code for first business starts here -->
<script>
$(document).on('change', 'select.Business1', function(){
var business1 = $('select.Business1 option:selected').val();
alert(business1);
var value = $(this).val();
$.ajax({
type:"POST",
data: { business1:business1 },
url: '<?php echo site_url('client_area/select_business_sub_cat'); ?>',
success : function (data){
$('#business2').empty();
$('#business2').append(data);
}
});
});
</script>
<!-- ajax code for first business ends here -->
// This script is not working. i can't find second change event.
<!-- ajax code for second business starts here -->
<script>
$(document).on('change','#business2',function(){
alert('Change Happened');
});
</script>
<!-- ajax code for second business ends here -->
I have tried with live() method also so alert called on first dropdown selection and then the ajax request calls so second drop down fills (Alternate for second script) ,
<script>
$(document).live('change', '#business2', function() {
alert('Change Happened');
});
</script>
Model function
public function select_business_sub_cat()
{
$business1 = $this->input->post('business1');
$result_sub_cat1 = $this->db->query("select category.id,subcategory.* From category LEFT JOIN subcategory ON category.id = subcategory.category_id where category.id = '$business1'");
$row_cat1 = $result_sub_cat1->result();
$data = array(
'id' => $row_cat1['0']->id,
'name' => $row_cat1['0']->name
);
echo "<option value='" . $row_cat1['0']->id . "'>" . $row_cat1['0']->name . "</option>";
// return $this->output->set_output($data);
}
View --
<div class="form-group">
<label>Business 1</label>
<select name="txtBusiness1" id="" style="height: 30px;width: 100%;" class="Business1">
<option value=""> Select Business </option>
<?php
$result_cat1 = $this->db->query("select * from category");
$row_cat1 = $result_cat1->result();
?>
<?php foreach($row_cat1 as $item){ ?>
<option value="<?php echo $item->id; ?>"><?php echo $item->name; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label>Business 2</label>
<select name="txtBusiness2" id="business2" style="height: 30px;width: 100%;" class="Business2">
<option value=""> Select Business2 </option>
</select>
</div>
<div class="form-group">
<label>Business 3</label>
<select name="txtBusiness4" id="business3" style="height: 30px;width: 100%;" class="Business3">
<option value=""> Select Business3 </option>
<?php echo $abc; ?>
</select>
</div>

Maybe that's because by calling $('#business2').html(data); you remove the event handlers, from jQuery documentation: http://api.jquery.com/html
When .html() is used to set an element's content, any content that was
in that element is completely replaced by the new content.
Additionally, jQuery removes other constructs such as data and event
handlers from child elements before replacing those elements with the
new content.
One option would be to use empty and append like this
$('#business2').empty();
$('#business2').append(data);
instead of $('#business2').html(data);

The Script which is not working for you !!!
<script>
$(document.body).on('change','#business2',function(){
alert('Change Happened');
});
</script>
Try this in place of the above script :
$(document).on("change", "#business2", function(){
alert('Change Happened');
});

Related

Getting value of the selected items php mysql html [duplicate]

I'm trying to populate a Select Box based in the choice of the first Select Box, but I'm having some troubles doing it. Simply nothing happens.
What I have until now (this is on my footer):
<script src="./plugins/bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select.category").change(function(){
var selectedCategory = $(".category option:selected").val();
$.ajax({
type: "POST",
url: "../inc/get_subcat.php",
data: { category : selectedCategory }
}).done(function(data){
$("#subcategory").html(data);
});
});
});
</script>
The page with the div is located at /pages/file.php:
<div class="col-md-6">
<div class="form-group">
<label class="control-label">SubCategory</label>
<div id="subcategory"> </div>
</div> </div>
The file that does the query is in another folder (inc/get_subcat.php):
<?php
include("config.php");
if(isset($_POST['category'])){
$cat = validar($_POST['category']);
$query = "SELECT id, subcategory FROM subcategories WHERE catid = ?";
#Prepare stmt or reports errors
($stmt = $mysqli->prepare($query)) or trigger_error($mysqli->error, E_USER_ERROR);
#Execute stmt or reports errors
$stmt->bind_param("i", $cat);
$stmt->execute() or trigger_error($stmt->error, E_USER_ERROR);
#Save data or reports errors
($stmt_result = $stmt->get_result()) or trigger_error($stmt->error, E_USER_ERROR);
#Check if are rows in query
if ($stmt_result->num_rows>0) {
echo "<select class='form-control' id='subcategory' name='subcategory'>";
# Save in $row_data[] all columns of query
while($row_data = $stmt_result->fetch_assoc()) {
# Action to do
echo "<option value='$row_data[id]'>$row_data[category]</option>";
}
echo "</select>";
}
$stmt->close();
}
?>
There is someone that could help me trying to fix this error? Can't fix despite trying for some hours.
Thanks!
Edit:
This is the HTML code with all Select Box:
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Category</label>
<select class='form-control' id='category' name='category'><option value='1'>Categoria 1</option><option value='2'>Categoria 2</option></select> </div>
</div>
<div class="col-md-6" id="subcategory">
</div>
</div>
In your HTML you have<select class='form-control'...etc
So the <select> has a class "form-control" only.
But your selector is $("select.category").change...etc. which means it's looking for a select with "category" in the class attribute (the dot . in the selector signifies a class). Such an element doesn't exist, hence why nothing happens.
Perhaps you meant to use the ID (in which case $("#category").change...etc)? Either that or you need to write <select class='form-control category'...etc before it will work.
May be problem in your array data or query. So please check it first.
I post here working example of depending drop down may be this will help you.
PHP code
$sub_category // Your array of Subcategory;
if ($sub_category) {
echo '<option value="">Sub Category</option>';
foreach ($sub_category as $sub_category) {
$selected = '';
if($sub_category['sub_category_id'] == $data['product']['sub_category_id'])
{
$selected = 'selected';
}
echo '<option value="' . $sub_category['sub_category_id'] . '" '.$selected.'>' . $sub_category['sub_category'] . '</option>';
}
}
JS code
<script type="text/javascript">
loadSubCategory();
jQuery(document).ready(function($) {
$(document).on('change', '.category_id', function(event) {
event.preventDefault();
loadSubCategory();
});
});
function loadSubCategory()
{
var category_id = $(".category_id option:selected").val();
$.ajax({
url: 'Your Path Of server Function',
type: 'post',
data: {category_id: category_id, product_id : "<?= $product['product_id']?>" },
cache: false,
success: function (resp) {
if(resp)
{
$('.sub_category_id').html(resp);
} else {
$('.sub_category_id').html('<option value="">Sub Category</option>');
}
}
})
}
</script>
HTML Code
<div class="form-group">
<b>Product Category </b>
<select class="form-control category_id" id="category_id" name="category_id">
<option>Category</option>
<?php
<option value="<?= $value['category_id'] ?>" <?=$selected ?> ><?= $value['category'] ?></option>
</select>
</div>
<!-- Category End -->
<!-- Sub Category Start -->
<div class="form-group">
<b>Product Sub Category </b>
<select class="form-control sub_category_id" name="sub_category_id">
<option value="">Sub Category</option>
<option value="">Sub Category</option>
<option value="20">Books Stationery</option>
<option value="21">Gaming and Accessories</option>
<option value="22">Music Musical Instruments</option>
</select>
</div>

Show sub-options based on selected main option in Codeigniter by ajax

I would like when I select the cats option that only the breed of cats appears, such as the Siamese example. If I select dog, I only want to get the breed of dogs, such as Pitbull and others.
Can you help me with the code, it tells me to use jquery, but how is it done I am just learning?
<div class="form-group">
<div class="row">
<div class="col-12 col-sm-6">
<label for="especie">Especie</label>
<select class="form-control" id="id_especie" name="id_especie" value="data-id-especie=">
<option value="">Seleccionar especie</option>
<?php foreach ($especie as $row) {?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['nombre']; ?></option>
<?php }?>
</select>
</div>
<div class="col-12 col-sm-6">
<label for="raza">Raza</label>
<select class="form-control" id="id_raza" name="id_raza">
<option value="">Seleccionar raza</option>
<?php foreach ($raza as $row) {?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['nombre']; ?></option>
<?php }?>
</select>
</div>
</div>
</div>
According to your Question you want Dynamic dependant drop down list in codeigniter with ajax / jQuery.
PHP VIEW :
<div class="col-12 col-sm-6">
<label for="especie">Especie</label>
<select class="form-control" id="id_especie" name="id_especie" value="data-id-especie=">
<option value="">Seleccionar especie</option>
<?php foreach ($especie as $row) {?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['nombre']; ?></option>
<?php }?>
</select>
</div>
<div class="col-12 col-sm-6">
<label for="raza">Raza</label>
<select class="form-control" id="id_raza" name="id_raza">
<!-- Data here will be auto populated by ajax -->
</select>
</div>
Controller :
public function get_data()
{
$id_especie = $this->input->post("id_especie");
$SUbCatdata = $this->db->get_where('tableName',array('id'=>$id_especie))->result_array();
$option ="<option selected disabled value=''>Select Name</option>";
foreach($SUbCatdata as $row)
{
$option.="<option value='".$row['id']."'>".$row['nombre']."</option>";
}
echo $option;
}
jQuery / Ajax :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#id_especie").on("change",function(){
var id_especie = $(this).val();
$.ajax({
url : "<?php echo base_url('Controller/get_data') ?>",
type: "post",
data: {"id_especie":id_especie},
success : function(data){
//alert(data);
$("#id_raza").html(data);
}
});
});
</script>
Note : For more info regarding change()
https://api.jquery.com/change
If I understand you correctly, you want to create a sub-dropdown list that is dependent on the selection of another (main) dropdown list. If this is the case, here's what you need to do.
First, you need to create a file that contains code that will fetch results based on what is supplied. That is (in your example), if the main category is "dogs", it will query the database for all "species" of dogs, and return the result. Something like this:
Category Controller
class Category_controller extends CI_Controller{
// Get Subcategory method
public function get_subcategory()
{
// Check if input ($_GET or $_POST) exists
if ( $this->input->post_get() )
{
$main_cat_id = $this->input->post_get('mainid'); // main category id
// Perform your db query here to get the subcategory of the main cat
// Echo the result after performing a foreach loop like you did in the
// html file. <option value="value_id">value name</option>
$result = ""; // store empty value first
foreach ($dbresult as $value)
{
$result .= '<option value="$value['id']">$value['nombre']</option>';
}
echo $result;
}
}
}
SubCategory.js
$(document).ready(function() {
$('select[name="id_especie"]').on('change', function() {
var catid = $(this).val(); // will get the value attribute of the selected main category
// Perform ajax request
$.ajax({
url: 'url-to-the-subcategory-controller', // remember to set this in your config/routes.php file
method: 'POST',
cache: false,
data: {mainid: catid},
dataType: 'html',
success: function(data) {
$('select#id_raza').html(data); // update the subcategory dropdown
},
error: function(data) {
console.log(data);
}
});
})
});
So, your second select box select#id_raza show look like so in your view file:
<div class="col-12 col-sm-6">
<label for="raza">Raza</label>
<select class="form-control" id="id_raza" name="id_raza">
<option value="">Seleccionar raza</option>
<!-- Data here will be auto populated by ajax -->
</select>
</div>

POST variable is null when using AJAX call

I am trying to POST the value selected in a dropdown list using AJAX call. But the POST variable remains blank when the value is selected from the dropdown.
I have used the ECHO method to check whether it is returning the POST value. But it is empty.
Here is the code for reference:
Javascript (Jquery and Ajax):
<script>
$(document).ready(function(){
$("#booking_date").change(function(){ //listen when the option change
var optionValue = $("#booking_date").val(); //get the new value
$.ajax({
url: "doctordetails.php", //php file which recive the new value and save it to the database
data: { optionValue: optionValue }, //send the new value
type: "POST" , //use POST method
success: function(data) {
console.log(optionValue);
}
});
});
});
</script>
HTML:
<div class="row">
<div class="col-6">
<div class="form-group">
<input class="form-control" type="text" id="booking_date" name="booking_date" data-lang="en" data-min-year="2017" data-max-year="2020" data-disabled-days="10/17/2017,11/18/2017">
</div>
</div>
<div class="col-6">
<div class="form-group">
<select class="form-control">
<option value="">Select slot</option>>
<?php
require_once("dblogin.php");
?>
<option value="<?php echo $_POST[" optionValue "]; ?>">
<?php echo $_POST["optionValue"]; ?>
</option>
</select>
</div>
</div>
</div>
Expected result:
$_POST should return the selected value from booking_date and the $_POST value will be used in a SQL Query.
If this is dropdown list, then id must be on select box. You set id booking_date on textbox other than select box. write as:
<select id="booking_date" class="form-control">
</select>
If you want to value from select(dropdown) so you have to set id on <select> rather than textbox <input>
<select id="booking_date" class="form-control">
<option value="">Select slot</option>>
<?php require_once("dblogin.php"); ?>
<option value="<?php echo $_POST["optionValue"]; ?>">
<?php echo $_POST["optionValue"]; ?>
</option>
</select>
On Script:
<script>
$(document).ready(function(){
$("#booking_date").change(function(){ //listen when the option change
var optionValue = $(this).val(); //get the new value
$.ajax({
url: "doctordetails.php", //php file which recive the new value and save it to the database
data: { getValue: optionValue }, //send the new value
type: "POST" , //use POST method
success: function(data) {
console.log(data);
}
});
});
});
</script>

Populate Select based on another Select

I'm trying to populate a Select Box based in the choice of the first Select Box, but I'm having some troubles doing it. Simply nothing happens.
What I have until now (this is on my footer):
<script src="./plugins/bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select.category").change(function(){
var selectedCategory = $(".category option:selected").val();
$.ajax({
type: "POST",
url: "../inc/get_subcat.php",
data: { category : selectedCategory }
}).done(function(data){
$("#subcategory").html(data);
});
});
});
</script>
The page with the div is located at /pages/file.php:
<div class="col-md-6">
<div class="form-group">
<label class="control-label">SubCategory</label>
<div id="subcategory"> </div>
</div> </div>
The file that does the query is in another folder (inc/get_subcat.php):
<?php
include("config.php");
if(isset($_POST['category'])){
$cat = validar($_POST['category']);
$query = "SELECT id, subcategory FROM subcategories WHERE catid = ?";
#Prepare stmt or reports errors
($stmt = $mysqli->prepare($query)) or trigger_error($mysqli->error, E_USER_ERROR);
#Execute stmt or reports errors
$stmt->bind_param("i", $cat);
$stmt->execute() or trigger_error($stmt->error, E_USER_ERROR);
#Save data or reports errors
($stmt_result = $stmt->get_result()) or trigger_error($stmt->error, E_USER_ERROR);
#Check if are rows in query
if ($stmt_result->num_rows>0) {
echo "<select class='form-control' id='subcategory' name='subcategory'>";
# Save in $row_data[] all columns of query
while($row_data = $stmt_result->fetch_assoc()) {
# Action to do
echo "<option value='$row_data[id]'>$row_data[category]</option>";
}
echo "</select>";
}
$stmt->close();
}
?>
There is someone that could help me trying to fix this error? Can't fix despite trying for some hours.
Thanks!
Edit:
This is the HTML code with all Select Box:
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Category</label>
<select class='form-control' id='category' name='category'><option value='1'>Categoria 1</option><option value='2'>Categoria 2</option></select> </div>
</div>
<div class="col-md-6" id="subcategory">
</div>
</div>
In your HTML you have<select class='form-control'...etc
So the <select> has a class "form-control" only.
But your selector is $("select.category").change...etc. which means it's looking for a select with "category" in the class attribute (the dot . in the selector signifies a class). Such an element doesn't exist, hence why nothing happens.
Perhaps you meant to use the ID (in which case $("#category").change...etc)? Either that or you need to write <select class='form-control category'...etc before it will work.
May be problem in your array data or query. So please check it first.
I post here working example of depending drop down may be this will help you.
PHP code
$sub_category // Your array of Subcategory;
if ($sub_category) {
echo '<option value="">Sub Category</option>';
foreach ($sub_category as $sub_category) {
$selected = '';
if($sub_category['sub_category_id'] == $data['product']['sub_category_id'])
{
$selected = 'selected';
}
echo '<option value="' . $sub_category['sub_category_id'] . '" '.$selected.'>' . $sub_category['sub_category'] . '</option>';
}
}
JS code
<script type="text/javascript">
loadSubCategory();
jQuery(document).ready(function($) {
$(document).on('change', '.category_id', function(event) {
event.preventDefault();
loadSubCategory();
});
});
function loadSubCategory()
{
var category_id = $(".category_id option:selected").val();
$.ajax({
url: 'Your Path Of server Function',
type: 'post',
data: {category_id: category_id, product_id : "<?= $product['product_id']?>" },
cache: false,
success: function (resp) {
if(resp)
{
$('.sub_category_id').html(resp);
} else {
$('.sub_category_id').html('<option value="">Sub Category</option>');
}
}
})
}
</script>
HTML Code
<div class="form-group">
<b>Product Category </b>
<select class="form-control category_id" id="category_id" name="category_id">
<option>Category</option>
<?php
<option value="<?= $value['category_id'] ?>" <?=$selected ?> ><?= $value['category'] ?></option>
</select>
</div>
<!-- Category End -->
<!-- Sub Category Start -->
<div class="form-group">
<b>Product Sub Category </b>
<select class="form-control sub_category_id" name="sub_category_id">
<option value="">Sub Category</option>
<option value="">Sub Category</option>
<option value="20">Books Stationery</option>
<option value="21">Gaming and Accessories</option>
<option value="22">Music Musical Instruments</option>
</select>
</div>

want to show selected divs after form submission also

Bellow shown code does these things
when i select Scholership Programs from select list the div element with class="mystaff_hide mystaff_opt1" will be shown
and then i select Family Income now div with class="mystaff_hide mystaff_opt2" will be shown. Now both are there on my window.
Up to this the code works fine
What i want is after submission of my form i want both of them are must be there on my window
<div class="row">
<div class="col-md-6 col-sm-6 pull-left">
<div class="form-group">
<legend>Options to Search</legend>
<select class="form-control firstdropdown" name="sel_options" id="mystuff">
<option>Select Options</option>
<option value="opt1">Scholership Programs</option>
<option value="opt2">Family Income</option>
</select>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6 mystaff_hide mystaff_opt1">
<div class="form-group">
<label for="LS_name">Scholarship</label>
<select class="form-control" name="LS_name[]" id="LS_name" multiple="multiple">
<option value="opt1">Scholership1</option>
<option value="opt2">Scholership2</option>
</select>
</div>
</div>
<div class="col-md-6 col-sm-6 mystaff_hide mystaff_opt2">
<div class="form-group">
<label for="Family Income">Family Income</label>
<select multiple class="form-control" name="FamilyIncome[]" id="FamilyIncome">
<option value="opt1">Family Income1</option>
<option value="opt2">Family Income2</option>
</select>
</div>
</div>
This is my script
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/multi-select/0.9.12/js/jquery.multi-select.min.js"></script>
<script>
$( document ).ready(function() {
$('.mystaff_hide').addClass('collapse');
$('#mystuff').change(function(){
var selector = '.mystaff_' + $(this).val();
$(selector).collapse('show');
});
});
</script>
After lot of search i got this code which is shows only recent related selected option's div
<?php if(isset($_POST['sel_options']) &&
!empty(isset($_POST['sel_options']))){
?>
<script>
var selected_option = "<?php echo $_POST['sel_options']; ?>";
var selector = '.mystaff_' + selected_option;
//show only element connected to selected option
$(selector).collapse('show');
</script>
<?php } ?>
Take a look at localStorage or sessionstorage to store information about the state of webpage and read them after reload to restore the UI state
Example:
Localstorage
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
Sessionstorage
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";
Or you may want to use AJAX
AJAX is the art of exchanging data with a server, and updating parts of a web page - without reloading the whole page.
As you are using jquery, you may want to look at using Ajax in jquery.
// this is the id of the form
$("#idForm").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});

Categories