I have 2 SelectOption where if Select 1 is selected, then Select 2 automatically synchronizes with Select 1
all SelectOptions contents retrieve from a database table.
SELECT 1 & 2 scripts:
<select name="leavetype" autocomplete="off">
<option value="">Choose Leave Type</option>
<?php $sql = "SELECT LeaveType from tblleavetype";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $result)
{ ?>
<option value="<?php echo htmlentities($result->LeaveType);?>"><?php echo htmlentities($result->LeaveType);?></option>
<?php }} ?>
</select>
<select name="rightsgranted" autocomplete="off">
<option value="">Rights Granted</option>
<?php $sql = "SELECT RightsGranted from tblleavetype";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $result)
{ ?>
<option value="<?php echo htmlentities($result->RightsGranted);?>"><?php echo htmlentities($result->RightsGranted);?></option>
<?php }} ?>
</select>
example
you need to use ajax for this work
this example is for the select city of a state
index.php
<?php
//Include the database configuration file
include 'dbConfig.php';
//Fetch all the country data
$query = $db->query("SELECT * FROM countries WHERE status = 1 ORDER BY country_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
?>
<select id="country">
<option value="">Select Country</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['country_id'].'">'.$row['country_name'].'</option>';
}
}else{
echo '<option value="">Country not available</option>';
}
?>
</select>
<select id="state">
<option value="">Select country first</option>
</select>
<select id="city">
<option value="">Select state first</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'country_id='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
}
});
}else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
}
});
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'state_id='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
<select id="state">
<option value="">Select country first</option>
</select>
<select id="city">
<option value="">Select state first</option>
</select>
ajax.php
<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'country_id='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
}
});
}else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
}
});
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'state_id='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
ajaxData.php
<?php
//Include the database configuration file
include 'dbConfig.php';
if(!empty($_POST["country_id"])){
//Fetch all state data
$query = $db->query("SELECT * FROM states WHERE country_id = ".$_POST['country_id']." AND status = 1 ORDER BY state_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
//State option list
if($rowCount > 0){
echo '<option value="">Select state</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['state_id'].'">'.$row['state_name'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}elseif(!empty($_POST["state_id"])){
//Fetch all city data
$query = $db->query("SELECT * FROM cities WHERE state_id = ".$_POST['state_id']." AND status = 1 ORDER BY city_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
//City option list
if($rowCount > 0){
echo '<option value="">Select city</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['city_id'].'">'.$row['city_name'].'</option>';
}
}else{
echo '<option value="">City not available</option>';
}
}
?>
see the full tutorial in this link
I Found simple method.
This might not be the best solution, but it should do the trick.
Maybe this will help others: http://jsfiddle.net/7BUmG/3876/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#leavetype').change(function() {
var rightsgranted = $(this).find("option:selected").attr("title");
$('#RightsGranted').val(rightsgranted);
});
});
</script>
<select id="leavetype" name="leavetype" autocomplete="off">
<option value="">Choose Leave Type</option>
<?php $sql = "SELECT LeaveType,RightsGranted from tblleavetype";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $result)
{ ?>
<option title="<?php echo htmlentities($result->RightsGranted);?>" value="<?php echo htmlentities($result->LeaveType);?>"><?php echo htmlentities($result->LeaveType);?></option>
<?php }} ?>
</select>
<input type='text' name="RightsGranted" id="RightsGranted" hidden/>
Related
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
}
?>
I am having significant issues trying to get the AJAX to fire on this PHP code.
I can get the first field populated without issue, however the AJAX call does not seem to populate the first dependency (and therefore the second). I am an AJAX newbie (and have googled extensively) but cannot seem to crack this one.
Note that the ladb.php file runs fine.
<?php
// Include the database config file
include_once 'ladb.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body style="background: #D5DDE0">
<div class="container">
<form action="" method="post">
<div class="form-group col-md-6">
<!-- Country dropdown -->
<label for="country">Country</label>
<select class="form-control" id="country">
<option value="">Select Country</option>
<?php
$query = "SELECT * FROM City_Index GROUP BY country ORDER BY country ASC";
$result = $ladb->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<option value='{$row["countryid"]}'>{$row['country']}</option>";
}
}else{
echo "<option value=''>Country not available</option>";
}
?>
</select><br>
<!-- State dropdown -->
<label for="admin">Administrative Area</label>
<select class="form-control" id="admin">
<option value="">Select Administrative Area</option>
</select><br>
<!-- City dropdown -->
<label for="city">city_ascii</label>
<select class="form-control" id="city">
<option value="">Select City</option>
</select>
</div>
</form>
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
// Country dependent ajax
$("#country").on("change",function(){
var country = $(this).val();
if (countryid) {
$.ajax({
url :"action.php",
type:"POST",
cache:false,
data:{countryid:countryid},
success:function(data){
$("#admin").html(data);
$('#city').html('<option value="">Select Administrative Area</option>');
}
});
}else{
$('#admin').html('<option value="">Select Country</option>');
$('#city').html('<option value="">Select Administrative Area</option>');
}
});
// state dependent ajax
$("#admin").on("change", function(){
var admin = $(this).val();
if (admin) {
$.ajax({
url :"action.php",
type:"POST",
cache:false,
data:{admin:admin},
success:function(data){
$("#city").html(data);
}
});
}else{
$('#city').html('<option value="">Select Administrative Area</option>');
}
});
});
</script>
The action.php file below
<?php
// Include the database config file
include_once 'ladb.php';
// Get country id through state name
$country = $_POST['country'];
if (!empty($country)) {
// Fetch state name base on country id
$query = "SELECT * FROM CityList WHERE country = {$country} GROUP BY admin_name_ascii";
$result = $ladb->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="'.$row['admin_id'].'">'.$row['admin_name_ascii'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}elseif (!empty($_POST['admin'])) {
$admin = $_POST['admin'];
// Fetch city name base on state id
$query = "SELECT * FROM CityList WHERE admin_id = {$admin}";
$result = $ladb->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="'.$row['cityid'].'">'.$row['city_ascii'].'</option>';
}
}else{
echo '<option value="">City not available</option>';
}
}
?>
Any help greatly appreciated!
Thanks to #zergski I note that one of references were defined (countryid in Line 53). DevTools is my new best friend.
Can someone help me on how to link up 2 dropdown list which data came from the same table in the database, is it possible to do this way because I can only find a solution which there must be 2 table in the database to link up those two. this is how should it work, 1st, the user choose the department and the 2nd dropdown will show only the people that assigned from that particular department.
database table has id,name,department.
the department works already but the 2nd dropdown didnt work to filter from the department. Can someone help me to know what is wrong with this?
index.php
<?php
$query ="SELECT DISTINCT company from hrar";
$results = $db_handle->runQuery($query);
?>
<script>
function getName(val) {
$.ajax({
type: "POST",
url: "getName.php",
data:'department='+val,
success: function(data){
$("#nameList").html(data);
}
});
}
function selectDepartment(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
</script>
<label>Department:</label><br/>
<select name="country" id="country-list" class="demoInputBox" onChange="getName(this.value);">
<option value="">Select Department</option>
<?php
foreach($results as $country) {
?>
<option value="<?php echo $country["id"]; ?>"><?php echo $country["company"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>Name:</label><br/>
<select name="state" id="nameList" class="demoInputBox">
<option value="">Select Name</option>
</select>
//below is the getName.php
if(!empty($_POST["company"])) {
$query ="SELECT DISTINCT name from hrar = '" . $_POST["company"] . "'";
$results = $db_handle->runQuery($query);
?>
<option value="">Select Name</option>
<?php
foreach($results as $name) {
?>
<option value="<?php echo $name["id"]; ?>"><?php echo $name["name"]; ?></option>
<?php
}
}
?>
Try this.
<select name="filter" id="filter" onchange="this.form.submit();">
<option value="name">Select Name</option>
<?php
$sql = "SELECT DISTINCT name FROM hr";
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_array($result))
{
echo "<option value='". $row['name'] ."'>" .$row['name'] ."</option>";
}
?>
</select>
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
}
}
?>
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....
}