How to cascade three dropdown using PHP and JS? - javascript

I have a custom page template with three dropdown, the values of each dropdown is populate dynamically. Now, I want to cascade it. Whatever option the user choose in 1st dropdown, the values that under of that option will be displayed as an options in 2nd dropdown, same as in the 3rd dropdown.
I have a JS snippet, but the cascading of the three dropdown is not working
Snippet PHP:
<form action='' method='post' name='test' id='test'>
<div class="div-select">
<label for="list_position" id="idname">Position</label>
<br/>
<select name="list_position" id="filterbypostion" onchange="app_position(this.form)">
<option name="default" class="filter_by" selected="selected" value="Select by Position">Select by Position</option>
<?php
foreach($query_location as $option){
if(isset($_POST['list_position']) && $_POST['list_position'] == $option->position)
echo '<option name="list_position" class="filter_by" selected value="'.$option->position.'">'.$option->position.'</option>';
else
echo '<option name="list_position" class="filter_by" value="'.$option->position.'">'.$option->position.'</option>';
};
?>
</select>
</div>
<div class="div-select">
<label for="list_position" id="idname">Position</label>
<br/>
<select name="list_position" id="filterbypostion" onchange="app_location(this.form)">
<option name="default" class="filter_by" selected="selected" value="Select by Position">Select by Position</option>
<?php
foreach($query_location as $option){
if(isset($_POST['list_position']) && $_POST['list_position'] == $option->position)
echo '<option name="list_position" class="filter_by" selected value="'.$option->position.'">'.$option->position.'</option>';
else
echo '<option name="list_position" class="filter_by" value="'.$option->position.'">'.$option->position.'</option>';
};
?>
</select>
</div>
<div class="div-select">
<label for="list_position" id="idname">Position</label>
<br/>
<select name="list_position" id="filterbypostion" onchange="app_location(this.form)">
<option name="default" class="filter_by" selected="selected" value="Select by Position">Select by Position</option>
<?php
foreach($query_location as $option){
if(isset($_POST['list_position']) && $_POST['list_position'] == $option->position)
echo '<option name="list_position" class="filter_by" selected value="'.$option->position.'">'.$option->position.'</option>';
else
echo '<option name="list_position" class="filter_by" value="'.$option->position.'">'.$option->position.'</option>';
};
?>
</select>
</div>
<div class="div-input">
<input type="submit" value="Search" class="div-input-submit"/>
</div>
</form>
Snippet JS:
function app_position(form){
var val=form.list_position.options[form.list_position.options.selectedIndex].value;
self.location='page-resume-databank?list_position=' + val ;
}
function app_location(form){
var val=form.list_position.options[form.list_position.options.selectedIndex].value;
var val2=form.list_location.options[form.list_location.options.selectedIndex].value;
self.location='page-namepage?list_location=' + val + '&list_processed=' + val2 ;
}

<form action='' method='post' name='resumeDatabank' id='resumeDatabank'>
<div class="div-select">
<label for="list_position" id="#ddress_search LABEL">Position</label>
<br/>
<select name="list_position" id="filterbypostion" onchange="app_position(this.value)">
<option name="default" class="filter_by" selected="selected" value="Select by Position">Select by Position</option>
<?php
foreach($query_location as $option){
if(isset($_POST['list_position']) && $_POST['list_position'] == $option->position)
echo '<option name="list_position" class="filter_by" selected value="'.$option->position.'">'.$option->position.'</option>';
else
echo '<option name="list_position" class="filter_by" value="'.$option->position.'">'.$option->position.'</option>';
};
?>
</select>
</div>
<div class="div-select" id="show_street">
<label for="list_position" id="#address_search LABEL">Street</label>
<br/>
<select name="list_position" id="filterbypostion">
<option name="default" class="filter_by" selected="selected" value="Select by Position">Select Road</option>
</select>
</div>
<div class="div-select" id="show_roads">
<label for="list_position" id="#address_search LABEL">Roads</label>
<br/>
<select name="list_position" id="filterbypostion">
<option name="default" class="filter_by" selected="selected" value="Select by Position">Select Road</option>
</select>
</div>
<div class="div-input">
<input type="submit" value="Search" class="div-input-submit"/>
</div>
</form>
<script>
function app_position(city){
//city is selected value of city drop down
//give the correct path to you ajax.php
$.ajax({
type: "POST",
url: 'ajax.php',
data: "city="+city+"type=street" ,
success: function(data)
{
$("#show_street").html(data);
}
});
}
function app_location(street){
//street is selected value of street drop down
//give the correct path to you ajax.php
$.ajax({
type: "POST",
url: 'ajax.php',
data: "street="+street+"type=roads" ,
success: function(data)
{
$("#show_roads").html(data);
}
});
}
</script>
in you ajax.php file
<?php
$type = $_POST['type'];//this type will load the relevant function.
if($type="street"){
$city = $_POST['city'];
//now get the value of streets belongs to this city
$your_query = "Select * from street_table where city_id=$city";//you can modify this query according to your table
$res = mysql_query($your_query);
?>
<label for="list_position" id="#address_search LABEL">Street</label>
<br/>
<select name="list_position" id="filterbypostion" onchange="app_location(this.value)">
<?php while($raws = mysql_fetch_assoc($res)){?>
<option name="default" class="filter_by" selected="selected" value="<?php echo $raws['street_id']?>"><?php echo $raws['street_name']?></option>
<?php }//END OF WHILE?>
</select>
<?php }//END OF IF CHECcing street option
if($type="roads"){
$street = $_POST['street'];
//now get the value of streets belongs to this city
$your_query_roads = "Select * from road_table where street_id=$street";////you can modify this query according to your table
$res_roads = mysql_query($your_query_roads);
?>
<label for="list_position" id="#address_search LABEL">Street</label>
<br/>
<?php while($raws_roads = mysql_fetch_assoc($res_roads)){?>
<input name="roads" type="radio" value="<?php echo $raws_roads['road_id'];?>">
<?php }//END OF WHILE?>
<?php
}
?>

You can do it in another way, the other two select box can be fetch from ajax request by posting which box you want , and the entire select box you can send from a component,
like :
$("#country").live("change", function(){
$.post("component.php", country:$(this).val(), function(data){
$("#state-div").html(data);
}
});
and same for other two.

Related

Jquery help for single select country state fetch data

here is a code for multiselect which is working fine for multiselect but i need this code to be work in single select , in this Code #Country list is simply getting list from option as you can see in code and when we select #country in dropdown the #state data is fetching from data base according to country selection
( Multi select is Working fine but i need this in Single select )
<script src="js/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<label for="country">Country</label> ( Simple Drop Down for Country )
<?php include "fetch_country.php"; ?>
<select id="country" name="country[]" multiple class="form-control" >
<option value="India" label="India">India</option>
<option value="USA" label="USA">USA</option>
<option value="UK" label="UK">UK</option>
<option value="Canada" label="Canada">Canada</option>
<option value="China" label="China">China</option>
</select>
<div class="col-sm-6">
<label for="state">State</label> ( Fetching State data from Database )
<select id="state" name="state[]" multiple class="form-control" >
<option disabled>Select Country First</option>
</select>
<button class="myButnsbmt" type="submit" name="update" value="Update">Submit</button>
</form>
<script>
$(document).ready(function(){
$('#country').multiselect({
nonSelectedText:'?',
buttonWidth:'250px',
maxHeight: 400,
onChange:function(option, checked){
var selected = this.$select.val();
if(selected.length > 0)
{
$.ajax({
url:"fetch_country.php",
method:"POST",
data:{selected:selected},
success:function(data)
{
$('#state').html(data);
$('#state').multiselect('rebuild');
}
})
}
}
});
$('#state').multiselect({
nonSelectedText: '?',
allSelectedText: 'All',
buttonWidth:'250px',
includeSelectAllOption: true,
maxHeight: 400,
enableFiltering:true
});
});
</script>
Html Part
<div class="container mt-5">
<div class="row">
<div class="card">
<div class="card-header">
<h2 class="text-success">Country State City Dropdown List in PHP MySQL Ajax - Tutsmake.COM</h2>
</div>
<div class="card-body">
<form>
<div class="form-group">
<label for="country">Country</label>
<select class="form-control" id="country-dropdown">
<option value="">Select Country</option>
<?php
require_once "db.php";
$result = mysqli_query($conn, "SELECT * FROM countries");
while ($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="form-group">
<label for="state">State</label>
<select class="form-control" id="state-dropdown">
</select>
</div>
<div class="form-group">
<label for="city">City</label>
<select class="form-control" id="city-dropdown">
</select>
</div>
</form>
</div>
</div>
</div>
</div>
js part
$(document).ready(function () {
$('#country-dropdown').on('change', function () {
var country_id = this.value;
$.ajax({
url: "states-by-country.php",
type: "POST",
data: {
country_id: country_id
},
cache: false,
success: function (result) {
$("#state-dropdown").html(result);
$('#city-dropdown').html('<option value="">Select State First</option>');
}
});
});
$('#state-dropdown').on('change', function () {
var state_id = this.value;
$.ajax({
url: "cities-by-state.php",
type: "POST",
data: {
state_id: state_id
},
cache: false,
success: function (result) {
$("#city-dropdown").html(result);
}
});
});
});
states-by-country.php
<?php
require_once "db.php";
$country_id = $_POST["country_id"];
$result = mysqli_query($conn, "SELECT * FROM states where country_id = $country_id");
?>
<option value="">Select State</option>
<?php
while ($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row["id"]; ?>"><?php echo $row["name"]; ?></option>
<?php
}
?>
cities-by-state.php
<?php
require_once "db.php";
$state_id = $_POST["state_id"];
$result = mysqli_query($conn, "SELECT * FROM cities where state_id = $state_id");
?>
<option value="">Select City</option>
<?php
while ($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row["id"]; ?>"><?php echo $row["name"]; ?></option>
<?php
}
?>
Then try this
<label for="country">Country</label>
<select id="country" name="country" multiple class="form-control">
<option value="India" label="India">India</option>
<option value="USA" label="USA">USA</option>
<option value="UK" label="UK">UK</option>
<option value="Canada" label="Canada">Canada</option>
<option value="China" label="China">China</option>
</select>
<label for="state">State</label> ( Fetching State data from Database )
<select id="state" name="state[]" multiple class="form-control">
<option disabled>Select Country First</option>
</select>
<button class="myButnsbmt" type="submit" name="update" value="Update">Submit</button>
<script>
$(document).ready(function() {
$('#country').on('change', function() {
var countryname = this.value;
$.ajax({
url: "states-by-country.php",
type: "POST",
data: {
country: countryname
},
cache: false,
success: function(result) {
$("#state-dropdown").html(result);
$('#city-dropdown').html('<option value="">Select State First</option>');
}
});
});
});
</script>
states-by-country.php
<?php
require_once "db.php";
$country = $_POST["country"];
$result = mysqli_query($conn, "SELECT * FROM states where countryname = $country");
?>
<option value="">Select State</option>
<?php
while ($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row["id"]; ?>"><?php echo $row["name"]; ?></option>
<?php
}
?>

how do i show selected value in option using jquery

i am trying to show a value from database to show in select option
running in PHP,JSON,AJAX,JQUERY
$(document).on('click', '.edit_data', function () {
var shop_id = $(this).attr("id");
$.ajax({
url: "<?php echo base_url();?>dashboard/update_shop",
method: "POST",
data: {shop_id: shop_id},
dataType: "json",
success: function (data) {
$('#emp_name').value = data[0].emp_id;
console.log(data[0].emp_id);
$('#shop_name').val(data[0].shop_name);
$('#shop_owner').val(data[0].shop_owner);
$('#shop_phone').val(data[0].shop_phone);
$('#shop_dist').val(data[0].shop_district);
$('#shop_loc').val(data[0].shop_location);
$('#shop_code').val(data[0].shop_code);
$('#shop_id').val(data[0].shop_id);
$('#latitude').val(data[0].latitude);
$('#longitude').val(data[0].longitude);
$('#create_button').text("Update");
$('#createOrder').modal('show');
}
});
});
i expect the out put comes like show data[0].emp_id as selected and show other option in dropdown
As your question is
how do i show selected value in option using jquery
and I can't comment as my reputation is below 50.
your answer should be $('#idOfSelectTag').val('3')
$(document).ready(function(){
$('#txtValue').change(function(){
changeValue($(this).val());
});
});
function changeValue(){
var value = $('#txtValue').val();
value = value==''? 1: value;
$('#selTest').val(value);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selTest">
<option value="1">one</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
<br />
<input type="text" id="txtValue" />
<br />
<button onclick="changeValue(4)">Change Value</button>
you can also using php without jquery.
<select class="custom-select col-12" id="lcount" name="lcount" data-validation="required" >
<option value="0" <?php if($sdata['lcount']=='0') echo 'selected="selected"'; ?>>select</option>
<option value="1" <?php if($sdata['lcount']=='1') echo 'selected="selected"'; ?>>1</option>
<option value="2" <?php if($sdata['lcount']=='2') echo 'selected="selected"'; ?>>2</option>
<option value="3" <?php if($sdata['lcount']=='3') echo 'selected="selected"'; ?>>3</option>
<option value="4" <?php if($sdata['lcount']=='4') echo 'selected="selected"'; ?>>4</option>
<option value="5" <?php if($sdata['lcount']=='5') echo 'selected="selected"'; ?>>5</option>
</select>

Selected values dropdownlist value using javascript

I get these type of array in my javascript function as shown in image.Now i want selected all city in my dropdownlist which i get in my javascript array.
I have tried it but i didn't get success.How to do it.
function searchitem(id,name)
{
var ADDRESS = value.Address;
console.log(ADDRESS);
$("#Address option[value='" + vin + "']").prop("selected", true);
}
HTML Code
<select class="ct-js-select ct-select-lg" multiple="multiple" id="Address" name="Address[]" style="margin-left:14px;">
<option value="any">Any</option>
<optgroup label="City">
<?php foreach($Locations_Response->city as $CITIES){ ?>
<option value="<?php echo $CITIES; ?>"><?php echo $CITIES; ?></option>
<?php } ?>
</optgroup>
</select>
You need a loop:
var ADDRESS = ['Aberdeen Twp.','2'];
$.each(ADDRESS,function(i,vin) {
$("#Address option[value='" + vin + "']").prop("selected", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="ct-js-select ct-select-lg" multiple="multiple" id="Address" name="Address[]" style="margin-left: 14px; " tabindex="-1">
<option value="any">Any</option>
<optgroup label="City">
<option value="Aberdeen Twp.">Aberdeen Twp.</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</optgroup>
</select>
<select id='slc' name='slc'>
<?php
for($c=0;$c<10;$c++)
{
echo"<option> ".$c." </option>";
}
?>
script here
var txt=$('#slc').find(":selected").text();

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
}
}
?>

Two dropdown with one onchange

Hi what I'm trying to do is I have 2 dropdown. I want that the ajax will only work if the two dropdown has value selected. And how do I pass the datas of the two?
Here is my code right now
SCRIPT
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "get_state.php",
data:'country_id='+val,
success: function(data){
$("#state-list").val(data);
}
});
}
</script>
INDEX
<label>Group:</label><br/>
<select name="country" id="country-list" class="demoInputBox" onChange="getState(this.value);">
<option value="">Select Group</option>
<?php
while($row = mysql_fetch_array($results)) {
?>
<option value="<?php echo $row["g_id"]; ?>"><?php echo $row["g_name"]; ?> </option>
<?php
}
?>
</select>
<label>Division:</label><br/>
<select name="division" id="div-list" class="demoInputBox" onChange="getState(this.value);">
<option value="">Select Division</option>
<?php
while($row = mysql_fetch_array($results2)) {
?>
<option value="<?php echo $row["d_id"]; ?>"><?php echo $row["div_name"]; ?> </option>
<?php
}
?>
</select>
getstate.php
<?php
include("dbcon2.php");
if(!empty($_POST["country_id"])) {
$query ="SELECT * FROM personnel_gdd WHERE pg_group = '" . $_POST["country_id"] . "' ";
$results = mysql_query($query) or die(mysql_error());
?>
<?php
$row = mysql_num_rows($results)
?>
<?php echo $row; ?>
PS: I know that mysql is deprecated. I'll change it as soon as this problem is fixed. Thanks!
change
onchange="getState()"
donot pass any value in onchange event. And change your script like this
<script>
function getState(val) {
var country = $("#country-list").val();
var div = $("#div-list").val();
if(country && div) {
$.ajax({
type: "POST",
url: "get_state.php",
data:{"country_id": country,"div":div},
success: function(data){
$("#state-list").val(data);
}
});
}
}
</script>
This answer is generic, not related to your data but you will can understand how to figure it out.
$('select').change(function() {
var group = $('#country-list').val();
var div = $('#div-list').val();
if (group == -1 || div == -1) {
alert('please select country and division');
}
else {
$.ajax({
type: "POST",
url: "get_state.php",
data:'country_id=' + country + '&=div_id' + div,
success: function(data){
$("#state-list").val(data);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<label>Group:</label>
<select name="country" id="country-list" class="demoInputBox">
<option value="-1">Select Group</option>
<option value="1">Country 1</option>
<option value="1">Country 1</option>
<option value="2">Country 2</option>
<option value="3">Country 3</option>
</select>
<br />
<label>Division:</label>
<select name="division" id="div-list" class="demoInputBox">
<option value="-1">Select Division</option>
<option value="1">Division 1</option>
<option value="2">Division 2</option>
<option value="3">Division 3</option>
</select>
Than you get the 2 values in the server and return the data to the client. Than put this data into the third dropdown.
HTML
<label>Country:</label><br/>
<select name="country" id="country-list" class="demoInputBox" onChange="getState(this.value);">
<option value="">Select Country</option>
<?php
$selq = "your query..............";
$selm = mysql_query($selq);
while($row = mysql_fetch_array($selm))
{
?>
<option value="<?php echo $row["country_id"]; ?>"><?php echo $row["name"]; ?> </option>
<?php
}
?>
</select>
<select name="state" id="state-list" >
</select>
Javascript function
function getState(val) {
$.ajax({
type: "POST",
url: "test2.php",
data:'country_id='+val,
success: function(data){
$("#state-list").append('<option value=""></option>');
$('#state-list').html(data);
}
});
}
Ajax PHP file
if(!empty($_POST["country_id"]))
{
$query ="your query............... ";
$results = mysql_query($query) or die(mysql_error());
while($fetch = mysql_fetch_array($results))
{
?>
<option value="<?php echo $fetch['id']?>" ><?php echo $fetch['name'] ?></option>
<?php
}
}
You only need to check if all values are different from -1 or "" or whatever - then build the data object and fire the Ajax:
JSnippet Demo
function runAjax() {
//Check both:
check = true;
$('select').each(function(){
console.log($(this).val())
if ($(this).val() == -1) {
$('span').text("Please select both.");
check = false
}
});
if (!check) return;
$('span').text("OK. submiting");
//Get the data:
var data = {
select1: $('#sel1').val(),
select2: $('#sel2').val()
};
//Go on with ajax....
}

Categories

Resources