Set the Option Available for Select Based on Another Select PHP

Set the option available for select based on another select php

Like it was said, you can use ajax.
There is a static non-ajax way of doing it, but this way it is better in the long run.

Basically, what you do with that jQuery is listen for a change in the continent select box, and when a change happens, you make a request to the server asking: "give me all the countries within this continent". You should have a database for this or you can map them in static objects just to test it out.

$('.continent').change(function() {
var id = $(this).val(); //get the current value's option
$.ajax({
type:'POST',
url:'<path>/getCountries',
data:{'id':id},
success:function(data){
//in here, for simplicity, you can substitue the HTML for a brand new select box for countries
//1.
$(".countries_container").html(data);

//2.
// iterate through objects and build HTML here
}
});
});

This would of course make you add the countries_container in the HTML like and inside it you would render the select:

<div class="countries_container"></div>

Now in the actual PHP code server side (getCountries) you could do something like:

$id = $_POST['id'];
if(isset($id) && <other validations>)){

// 1. your query to get countries from a given continent
// and for each result you can build the HTML itself

// 2. OR, a better solution is to return an Object and then in the
// success:function(data){ } iterate through it
}

This code can most defiantly be improved, but I tried to explain it in a understandable way.

Also, you should check:

Jquery ajax populate dropdown with json response data

Demo of linked drop down list by using Ajax & PHP

Keep on mind, these were the first results from a google search therefore, next time, try to search within stack overflow itself to avoid duplicate questions.

Show drop down values of a select based on another select

You can add an event listener for the onChange event of the select box.
On the change event get the value of the select box and send its value to the server using an ajax request and fetch the value you want to show in the second select box based on the first one's value and show it in the second select box.
Example Code for state selection based on country selection:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Populate City Dropdown Using jQuery Ajax</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "process-request.php",
data: { country : selectedCountry }
}).done(function(data){
$("#response").html(data);
});
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td>
<label>Country:</label>
<select class="country">
<option>Select</option>
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
</select>
</td>
<td id="response">
<!--Response will be inserted here-->
</td>
</tr>
</table>
</form>
</body>
</html>

Backend:

<?php
if(isset($_POST["country"])){
// Capture selected country
$country = $_POST["country"];

// Define country and city array
$countryArr = array(
"usa" => array("New Yourk", "Los Angeles", "California"),
"india" => array("Mumbai", "New Delhi", "Bangalore"),
"uk" => array("London", "Manchester", "Liverpool")
);

// Display city dropdown based on country name
if($country !== 'Select'){
echo "<label>City:</label>";
echo "<select>";
foreach($countryArr[$country] as $value){
echo "<option>". $value . "</option>";
}
echo "</select>";
}
}
?>

How to change a select option based on choosing other select option

Here i got the answer.
Script file :

<script type="text/javascript">$(document).ready(function(){    $('#maincategory').on('change',function(){        var mainactegory_ID = $(this).val();        if(mainactegory_ID){            $.ajax({                type:'POST',                url:'ajaxData.php',                data:'mainactegory_ID='+mainactegory_ID,                success:function(html){                    $('#subcat1').html(html);                    $('#subcat2').html('<option value="">Select sub 1</option>');                 }            });         }else{            $('#subcat1').html('<option value="">Select main cat</option>');            $('#city').html('<option value="">Select sub cat 1</option>');         }    });        $('#subcat1').on('change',function(){        var subcat1_id = $(this).val();        if(subcat1_id){            $.ajax({                type:'POST',                url:'ajaxData.php',                data:'subcat1_id='+subcat1_id,                success:function(html){                    $('#city').html(html);                }            });         }else{            $('#city').html('<option value="">select sub 1</option>');         }    });});</script>
     <div class="form-group">      <label style="align-content:center" for="inputdefault">Select a category</label>           <?php       $maincategory= "select * from noorizone.categories where parent=''";       $result2= $con->query($maincategory);      ?>      <select class= "form-control" name="maincategory" id="maincategory">      <option value='0' > Select category</option>      <?php       while($row = mysqli_fetch_array($result2))         echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';             ?>      </select>           </div>                         <div class="form-group">     <label style="align-content:center" for="inputdefault">Sub category 1</label>      <select class="form-control" name="subcat1" id="subcat1">            </select>          </div>               <div class="form-group">      <label style="align-content:center" for="inputdefault">Sub category 1</label>      <select class="form-control" name="city" id="city">      </select>     </div>

Select based on another select using php

The following example of simple chained select menus ought to gie you an idea how you can accomplish your goals - you would need to study this and implement database calls but to test you can copy the entire piece of code, save to

<?php
/*
Include other PHP files/libraries,
set the session etc etc

.....
*/

if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) && $_POST['action']=='get_dependant_menu' ){
ob_clean();

$action=filter_input( INPUT_POST, 'action', FILTER_SANITIZE_STRING );
$id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT );

if( $action && $id && !is_nan( $id ) ){
/*

In production you would use the supplied POST values to query the database
and process the recordset - sending back the results as formatted HTML to
the AJAX callback function.

For the sake of demonstration though the script simply sends back data from a
simple loop...

sql=select * from table where id=? etc

*/

for( $i=1; $i <= 10; $i++ )echo "<option value='Service-$id-$i'>Service-$id-$i";
}
exit();
}
?>
<!doctype html>
<html>
<head>
<title>Dependent / Chained SELECT menus</title>
<script type='text/javascript' charset='utf-8'>
/* Basic Ajax function */
function ajax(m,u,p,c,o){
/*
m=Method,
u=Url,
p=Params,
c=Callback,
o=Options
*/
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
};

var params=[];
for( var n in p )params.push(n+'='+p[n]);

switch( m.toLowerCase() ){
case 'post': p=params.join('&'); break;
case 'get': u+='?'+params.join('&'); p=null; break;
}

xhr.open( m.toUpperCase(), u, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( p );
}

/* Callback function to populate second menu */
function createmenu(r,o,h){
/*
r=response
o=options ( sent by ajax function )
h=response headers
*/
o.menu.innerHTML=r;
}

function bindEvents(){
/* Get references to the two dropdown menus */
var oSelItem=document.querySelector('select[name="item1"]');
var oSelService=document.querySelector('select[name="service1"]');

/* Assign an `onchange` event listener */
oSelItem.onchange=function(e){

var method='post';
var url=location.href;

/* the parameters to send to the PHP script */
var params={
'action':'get_dependant_menu',
'id':this.options[ this.options.selectedIndex ].value
};

/* Options to pass to the ajax callback */
var opts={
menu:oSelService
};

/* make the ajax request */
ajax.call( this, method, url, params, createmenu, opts );

}.bind( oSelItem );
}

document.addEventListener( 'DOMContentLoaded', bindEvents,false );
</script>

<style type='text/css' charset='utf-8'>
select {padding:1rem;width:300px;}
</style>
</head>
<body>
<h1>Chained select menus using basic ajax</h1>
<form method='post'>

<select name='item1' class='country'>
<?php
/*
In production your code would use a database call
to populate the menu but for example purposes it
simply uses a loop
*/

for( $i=1; $i <= 10; $i++ )echo "<option value=$i>Item $i";

?>
</select>

<select name='service1' class='country'>
</select>
</form>
</body>
</html>

I don't know why you were unable or unwilling to attempt to implement the above AJAX solution with your own database code but after your persistant pleading perhaps the following will give you a better idea. This has NOT been tested!

<?php

if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) && $_POST['action']=='get_dependant_menu' ){
ob_clean();

$action=filter_input( INPUT_POST, 'action', FILTER_SANITIZE_STRING );
$id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_STRING );

if( $action && $id && !empty( $id ) ){

$sql='select * from service where irn = :irn order by sr asc';
$stmt->bindParam(':irn',$id);
$stmt->execute();

if( $stmt->rowCount() > 0 ){
while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
echo "<option value='{$row['IRN']}'>{$row['Name']}";
}
}
}
exit();
}
?>
<!doctype html>
<html>
<head>
<title>Dependent / Chained SELECT menus</title>
<script type='text/javascript' charset='utf-8'>
function ajax(m,u,p,c,o){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
};

var params=[];
for( var n in p )params.push(n+'='+p[n]);

switch( m.toLowerCase() ){
case 'post': p=params.join('&'); break;
case 'get': u+='?'+params.join('&'); p=null; break;
}

xhr.open( m.toUpperCase(), u, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( p );
}
function createmenu(r,o,h){
o.menu.innerHTML=r;
}

function bindEvents(){
var oSelItem=document.querySelector('select[name="item1"]');
var oSelService=document.querySelector('select[name="service1"]');
oSelItem.onchange=function(e){

var method='post';
var url=location.href;
var params={
'action':'get_dependant_menu',
'id':this.options[ this.options.selectedIndex ].value
};
var opts={
menu:oSelService
};
ajax.call( this, method, url, params, createmenu, opts );
}.bind( oSelItem );
}
document.addEventListener( 'DOMContentLoaded', bindEvents,false );
</script>
<style type='text/css' charset='utf-8'>
select {padding:1rem;width:300px;}
</style>
</head>
<body>
<h1>Chained select menus using basic ajax</h1>
<form method='post'>

<select name='item1' class='country'>
<?php

$sql='select * from `item` order by `sr` asc;';
$stmt=$user_home->runQuery( $sql );
$stmt->execute();

if( $stmt->rowCount() > 0 ){
while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
echo "<option value='{$row['IRN']}'>{$row['Name']}";
}
}

?>
</select>
<select name='service1' class='country'>
</select>
</form>
</body>
</html>

When a new row is added using the Add Row button the onchange event handlers registed above in the bindEvents function will NOT be cloned with the newly added select menu. To ensure that any & all newly added select menus use the same mechanism ( ie: ajax ) then the easiest to implement solution is to assign inline event handlers to the item dropdown menu. The javascript above can be changed to ( not tested btw )

<script type='text/javascript' charset='utf-8'>
/* AJAX FUNCTION */
function ajax(m,u,p,c,o){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
};

var params=[];
for( var n in p )params.push(n+'='+p[n]);

switch( m.toLowerCase() ){
case 'post': p=params.join('&'); break;
case 'get': u+='?'+params.join('&'); p=null; break;
}

xhr.open( m.toUpperCase(), u, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( p );
}

/* AJAX CALLBACK */
function createmenu(r,o,h){
o.menu.innerHTML=r;
}

/* INLINE EVENT HANDLER */
function evtselect(e){
try{
var el=e.target;
/* it is NOT necessary to have the `action` parameter... that was for testing for me initially */
var params={
'action':'get_dependant_menu',
'id':el.value
};

/*

newly added nodes ( add row ) should have their names changed*/
so the following line needs attention! Basically you need to find, in the DOM,
the next select menu on the same row ( think parentNode, nextSibling etc etc )

The following is NOT tested......!!!!!
*/
var td=el.parentNode.nextSibling;

var opts={
menu:td.querySelector('select')
};
ajax.call( this, method, url, params, createmenu, opts );
}catch( err ){
console.log( err );
}
}
</script>

To use the inline event handler you would typically do:

<select name='item' onchange='evtselect(event)'>/* options */</select>

how to change value of select options based on another select option selected?

Successfully Done...

Ajax function =>

$(document).ready(function () {
$('#location').on('change', function () {
var location_id = $(this).val();

if (location_id == '') {
$('#fees').prop('disabled', true);
} else {
$('#fees').prop('disabled', false);
$.ajax({
url: "<?php echo $base_url;?>welcome/getFeePeriod",
type: 'POST',
data: {location: location_id},
dataType: 'json',
success: function (data) {
//alert("Ok");
$('#fees').html(data);
},
error: function () {
alert("Error Accured...");
}
});
}
});
});

Controller function =>

public function getFeePeriod()
{
$location_id = $this->input->post('location');
$FeesPeriod = $this->admin_model->getFeePeriod($location_id);
if (count($FeesPeriod)>0) {
$fee_select_box = '';
$fee_select_box .= '<option id="">Select Fee Period</option>';
foreach ($FeesPeriod as $fees) {
$fee_select_box .= '<option id="' . $fees->admission_fee_1 . '">Monthly</option>+
<option id="' . $fees->admission_fee_3 . '">Quarterly</option>+
<option id="' . $fees->admission_fee_6 . '">Half Yearly</option>+
<option id="' . $fees->admission_fee_12 . '">Yearly</option>';
}
echo json_encode($fee_select_box);
}
}

model function =>

function getFeePeriod($location_id){
$query = $this->db->get_where('location', array('id'=>$location_id));
return $query->result();
}

Thanks everyone for their response...

I want to get dropdown values based on previous dropdown selection PHP

Focussing on these two SELECT menus only and using just a small piece of Javascript you could try something like the following. The javascript event listener issues a GET request when there is a change event on the first dropdown. The querystring parameter campus is then used in the sql satement for the 2nd dropdown.

<select name="campusselect">
<?php
$result= $conn->query("select `campus_name` from `campus`");
while( $row = $result->fetch_assoc() ) {
printf( '<option>%s', $row['campus_name'] );
}
?>
</select>

<script>
document.querySelector('select[name="campusselect"]').addEventListener('change', function(e){
location.search='campus='+this.value;
});
</script>

<!--room drop down-->
<select name="roomsselect">
<?php
if( isset( $_GET['campus'] ) ){
$sql='select `room_name` from `rooms` where `room_campus`=?';
$stmt=$conn->prepare($sql);
$stmt->bind_param('s',$_GET['campus']);
$res=$stmt->execute();
$stmt->bind_result($room);

while( $stmt->fetch() )printf('<option>%s',$room);
}
?>
</select>

how to change a selections options based on another select option selected?

Here is an example of what you are trying to do => fiddle

$(document).ready(function () {    $("#type").change(function () {        var val = $(this).val();        if (val == "item1") {            $("#size").html("<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option>");        } else if (val == "item2") {            $("#size").html("<option value='test'>item2: test 1</option><option value='test2'>item2: test 2</option>");        } else if (val == "item3") {            $("#size").html("<option value='test'>item3: test 1</option><option value='test2'>item3: test 2</option>");        } else if (val == "item0") {            $("#size").html("<option value=''>--select one--</option>");        }    });});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><select id="type">    <option value="item0">--Select an Item--</option>    <option value="item1">item1</option>    <option value="item2">item2</option>    <option value="item3">item3</option></select>
<select id="size"> <option value="">-- select one -- </option></select>

How do I set the selected item in a drop down box

You need to set the selected attribute of the correct option tag:

<option value="January" selected="selected">January</option>

Your PHP would look something like this:

<option value="January"<?=$row['month'] == 'January' ? ' selected="selected"' : '';?>>January</option>

I usually find it neater to create an array of values and loop through that to create a dropdown.



Related Topics



Leave a reply



Submit