Dynamic generate form based on select box change value - php

I want to generate dynamic form based on select box change value.
Suppose i have a parent select box :
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
below select box is depend on first
<select name="select2" id="select2">
<option value="banana">Banana</option>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
</select>
Here is my 2 select boxes and i want 2 things
1) create dependency of 2 this select box
2 ) I want to generate a dynamic form based on change second select box value.
for example if i select apple then a form open with related apple value.
I am a new in jquery and i do not have any idea about it ( share me code script if any one knows)

You can follow this way to making a dynamic dropdown.
The following HTML code contains dependent dropdowns for countries and states. Country options are read from the database and shown in the dropdown on page load. Initially, the state dropdown has no options. On changing the country dropdown values, a jQuery function is called to get dependent state options and loaded dynamically.
<div class="frmDronpDown">
<div class="row">
<label>Country:</label><br/>
<select name="country" id="country-list" class="demoInputBox" onChange="getState(this.value);">
<option value="">Select Country</option>
<?php
foreach($results as $country) {
?>
<option value="<?php echo $country["id"]; ?>"><?php echo $country["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>State:</label><br/>
<select name="state" id="state-list" class="demoInputBox">
<option value="">Select State</option>
</select>
</div>
</div>
The following jQuery script shows a function to send an AJAX request to PHP to read state list depends on the selected country. This AJAX call is set with the selected country id.
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "get_state.php",
data:'country_id='+val,
success: function(data){
$("#state-list").html(data);
}
});
}
</script>
In PHP, it connects the database to retrieve “states” table values based on the country id passed by jQuery AJAX call. It forms state dropdown options and returns as the AJAX response. This response is inserted to the state dropdown.
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["country_id"])) {
$query ="SELECT * FROM states WHERE countryID = '" . $_POST["country_id"] . "'";
$results = $db_handle->runQuery($query);
?>
<option value="">Select State</option>
<?php
foreach($results as $state) {
?>
<option value="<?php echo $state["id"]; ?>"><?php echo $state["name"]; ?></option>
<?php
}
}
?>

Related

how to keep drop down selected values after pressing submit button in php?

enter image description hereI am using a dropdown list to show values in data tables. it's working but after press search button the dropdwon list clears.
<select name="staff" required>
<option value="">Select Staff</option>
<?php
$query_subject = mysql_query("SELECT * from staffdet");
while($row_subject = mysql_fetch_array($query_subject)) {
?>
<option value="<?php echo $row_subject['staff_code'];?>"><?php echo $row_subject['staff_code']."-".$row_subject['staff_name'];?></option>
<?php } ?>
</select>
How to keep selected dropdown list values?
IF you are submitting a form on same page with POST method then below code will solve your problem
<select name="staff" required>
<option value="">Select Staff</option>
<?php
$query_subject = mysql_query("SELECT * from staffdet");
while($row_subject = mysql_fetch_array($query_subject)) {
?>
<option value="<?php echo $row_subject['staff_code'];?>" <?php if(!empty($_POST['staff']) && $_POST['staff']==$row_subject['staff_code']){echo 'selected="selected"';}?>>
<?php echo $row_subject['staff_code']."-".$row_subject['staff_name'];?>
</option>
<?php } ?>

retrieve selected value in form_dropdown() and act on it in the same view

I am using codeigiter's form_dropdown() and would like to make the selection alter data farther down in the same view without submitting the form.
In the view php file:
echo form_dropdown('department_select',$options,'1');
<?php $test_list = $this->trainingmodel->get_dept_tests($deptselected); ?>
I would like $deptselected to reflect what the user has selected in the form_dropdown(). I would like this to update every time the user changes their dropdown selection but without submitting the form.
Things like the following would work if the form was submitted, but not before:
$deptselected = $_POST['department_select'];
or
$deptselected = $this->input->post('department_select');
There must be a way to do what I want using javascript, or onchange or the 4th input parameter to form_dropdown().
You can use the chained select jquery plugin http://www.appelsiini.net/projects/chained
A simple example taken from the website:
<select id="mark" name="mark">
<option value="">--</option>
<option value="bmw" selected>BMW</option>
<option value="audi">Audi</option>
</select>
<select id="series" name="series">
<option value="--">--</option>
</select>
<select id="engine" name="engine">
<option value="--">--</option>
</select>
<select id="transmission" name="transmission">
<option value="--">--</option>
</select>
And on
$("#transmission").remoteChained({
parents : "#engine",
url : "/api/transmissions.json",
depends : "#series"
});
You can set the ajax url to your Codeigniter controller that will serve the data to the view in json format.

Show/hide select values based on previous select choice

I have 2 select's inside a form. The second select has about 2000 lines in total coming out of my mysql table. One of the column into that mysql has 1 of the values used into the first select. I want to be able to filter on that value when it is selected into the first select, so that it only shows these articles.
code now:
<div class="rmaform">
<select name="discipline" class="discipline">
<option value=" " selected></option>
<option value="access">ACCESS</option>
<option value="inbraak">INBRAAK</option>
<option value="brand">BRAND</option>
<option value="cctv">CCTV</option>
<option value="airphone">AIRPHONE</option>
<option value="perimeter">PERIMETER</option>
</select>
</div>
<div class="rmaform">
<select name="article" class="input-article">
<?php
$articleselect = $dbh->prepare('SELECT * FROM articles');
$articleselect->execute();
while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
<?php
}
?>
</select>
I think i have to use Javascript for it but how do you combine PHP and Javascript? And what would be the best way to make the filter work?
jQuery for the change event and AJAX
$(document).ready(function(e) {
$('select.discipline').change(function(e) { // When the select is changed
var sel_value=$(this).val(); // Get the chosen value
$.ajax(
{
type: "POST",
url: "ajax.php", // The new PHP page which will get the option value, process it and return the possible options for second select
data: {selected_option: sel_value}, // Send the slected option to the PHP page
dataType:"HTML",
success: function(data)
{
$('select.input-article').append(data); // Append the possible values to the second select
}
});
});
});
In your AJAX.php
<?php
if(isset($_POST['selected_option']))
$selected_option=filter_input(INPUT_POST, "selected_option", FILTER_SANITIZE_STRING);
else exit(); // No value is sent
$query="SELECT * FROM articles WHERE discipline='$selected_option'"; // Just an example. Build the query as per your logic
// Process your query
$options="";
while($query->fetch()) // For simplicity. Proceed with your PDO
{
$options.="<option value='option_value'>Text for the Option</option>"; // Where option_value will be the value for you option and Text for the Option is the text displayed for the particular option
}
echo $options;
?>
Note: You can also use JSON instead of HTML for much simplicity. Read here, how to.
First give both of the selects an unique ids...
<div class="rmaform">
<select name="discipline" class="discipline" id="discipline">
<option value="" selected></option>
<option value="access">ACCESS</option>
<option value="inbraak">INBRAAK</option>
<option value="brand">BRAND</option>
<option value="cctv">CCTV</option>
<option value="airphone">AIRPHONE</option>
<option value="perimeter">PERIMETER</option>
</select>
</div>
<div class="rmaform">
<select name="article" class="input-article" id="article">
<option value="" selected></option>
</select>
Now you can use jQuery Ajax call to another file and get the HTML Response from that file and Populate in the select field with id="article" like this...
<script type="text/javascript">
$(document).ready(function(){
$("#discipline").change(function(){
var discipline = $(this).val();
$.post(
"ajax_load_articles.php",
{discipline : discipline},
function(data){
$("#article").html(data);
}
)
});
});
</script>
Now create a new file like ajax_load_articles.php... in the same directory where the html file exists... You can place it anywhere but then you have to change the $.post("url", the url to the ajax submission.
Contents of ajax_load_articles.php :
<?php
$discipline = $_POST["discipline"];
$articleselect = $dbh->prepare("SELECT * FROM articles WHERE colname = '{$discipline}'");
$articleselect->execute();
echo '<option value="" selected></option>';
while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
<?php
}
?>
Now when ever you will change the select of the first select field an Ajax call will take place and the data of the second select field will automatically adjust to related data selected in the first select field.
This is an example where you can select the college specific to the state ..
Form.php
// your code for form ...
// select box for state starts
<div class="form-group">
<label for="select" class="col-lg-2 col-md-2 control-label">State</label>
<div class="col-lg-10 col-md-10">
<select class="form-control input-sm" name="statename" id="stateid">
<option value="">---- Select ----</option>
<?php
$state=sql::readResultArray("Your Query To select State`");
foreach($state as $s){
?>
<option value="<?php echo $s?>"> <?php echo $s ?> </option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="select" class="col-lg-2 col-md-2 control-label">Colleges</label>
<div class="col-lg-10 col-md-10">
<select class="form-control input-sm" name="mycollegename">
<option value="">--- Select --- </option>
</select>
</div>
</div>
// further code for from in form.php..
Script to find the state and then pass the value to find the respective colleges in that state
<script>
$(document).ready(function(e) {
$('#stateid').change(function()
{ ids=$('#stateid').val();
$.get('mycollege.php', {type:ids} ,function(msg){
$('select[name="mycollegename"]').html(msg);
});
});
});
</script>
Call this file through ajax .. Code on this file
mycollege.php
<?php
require('db.php'); // call all function required, db files or any crud files
$type=$_GET['type'];
if(!empty($type)){
$r=sql::read("Your Query To call all teh college list");
?>
<select name="mycollegename">
<option value="">Select One</option>
<?php
foreach($r as $r){
echo "<option value=\"$r->collegename\">$r->collegename </option>";
}
?>
</select>
<?php }else{ ?>
<select name="mycollegename">
<option value="">Select State</option>
</select>
<?php } ?>

Retain select option value that are dependent on other select box - country state city

I have a form in which i display all countries from database, based on the the country selected state is populated and based on state, city is populated using jquery. Everything is working fine. Problem is when page is submitted and reloaded i am able to only retain country but not able to retain state and city select boxes as they get dynamically populated using onChange event fired with select option. Issue is under select boxes of state and city i do not do anything and hence when page reloads i do not get values entered by user. Any help on this is appreciated.
Following is the code
included in php -
<select name='country' onChange='selectCity(this.options[this.selectedIndex].value)'>
<option value='%'>Select Country</option>"
.$searchController->CreateCSCValues($searchController->GetCSCCountries(),'country').
"</select>
<select name='state' id='state_dropdown' onChange='selectState(this.options[this.selectedIndex].value)'>
<option value='%'>Select State</option>
</select>
<select name='city' id='city_dropdown'>
<option value='%'>Select City</option>
</select>
Javascript/jquery -------
function selectCity(country_id){
loadData('state',country_id);..........}
function selectState(state_id){
loadData('city',state_id);......... and then }
function loadData(loadType,loadId){
var dataString = 'loadType='+ loadType +'&loadId='+ loadId;
src="image/loading.gif" />');
$.ajax({D
type: "POST",
url: "get-State-City.php",
data: dataString,
cache: false,
success: function(result){
$("#"+loadType+"_loader").hide();
$("#"+loadType+"_dropdown").append(result);
}
});
in file get-State-City.php - loadtype and loadid are passed and depending on loadtype either state or city table is accessed and values displayed under state/city dropdown boxes.
I think it's easier then you think. Because your scripts only run on a onchange event, you can prefill the dropboxes, and you don't even have to change anything to your javascripts. Example:
<select name='country' onChange='selectCity(this.options[this.selectedIndex].value)'>
<option value='%'>Select Country</option>
<?php if( /* country is given */ ): ?>
<?php foreach($countries as $country): ?>
<?php $selected = $country->id == $selected_country_id ? ' selected="selected" : ''; ?>
<option value="<?php echo $country->id; ?>"<?php echo $selected; ?>><?php echo $country->name; ?></option>
<?php endforeach; ?>
<?php else: ?>
<?php echo $searchController->CreateCSCValues($searchController->GetCSCCountries(),'country'); ?>
<?php endif; ?>
</select>
// the same for the other two dropdowns
Now everything is prefilled (if any value is given), and the onchange still works. easy does it! :)

Change the list of dropdown according to the selection of other dropdown

I have two dropdowns .i want second dropdown list shoul changed according to the value selected in first dropdown.
this is my first dropdown
Category :<select name="Category" id="a1_txtBox5" required="required">
<option value="select">select..</option>
<?php while($selectcategoryarray=mysql_fetch_array($selectcategory)) {
?>
<option value="<?php echo $selectcategoryarray[1];?>"><?php echo $selectcategoryarray[1];?></option>
<?php
}
?>
</select>
And here is my second dropdown:
<label style="margin-left:24px;">Subcategory :</label><select style="margin-right:35px;" name="subcategory" id="a1_txtBox3" required="required">
<option value="select"> select..</option>
<?php while($selectsubcategoryarray=mysql_fetch_array($selectsubcategory)) {
?>
<option value="<?php echo $selectsubcategoryarray[2];?>"><?php echo $selectsubcategoryarray[2];?></option>
<?php
}
?>
</select>
Please help.
Exactly you need to handle the Change Event for your first Select element and in the body of the event you need to send request to server for getting data of second Select element.
I recommend to use an ajax process to doing this.
And o this you should use jQuery for handling events and have ajax.

Categories