Currently I have 2 select boxes called Country and City. Now I've made it so that the city data is populated according to the value selected in country using AJAX. To do this I've used the following code:
edit.php:
<select name="country" onchange="getcities($(this).val())" required>
<option value="<?php echo set_value('country'); ?>">Select Country</option>
<?php if($countries) foreach($countries as $country): ?>
<option value="<?php echo $country['id']; ?>" <?php echo ($listing[0]['country'] == $country['id'])?'selected="selected"':''?>><?php echo $country['name']; ?></option>
<?php endforeach; ?>
</select>
<label class="control-labels ">City</label>
<div id="emiratewrap">
<select name="emirate" id="emirate">
<option value="">Select City</option>
</select>
AJAX
$(document).ready(function () {
getcities($('#country').val());
});
function getcities(obj){
console.log(obj);
var dataString = new Object();
dataString.emirate = '<?php echo $property->emirate ?>';
$.ajax({
type: "get",
dataType:"json",
url: "<?php echo site_url('listings/ajaxgetcitiesedit'); ?>/"+obj,
data: dataString,
success: function(e) { $('#emiratewrap').html(e.result);
$bb = "<?php echo $property->status; ?>";
if($bb=="Y") {$("#emiratewrap select").addClass("disabled"); }
}
});
}
Controller:
function ajaxgetcitiesedit($country=''){
$emirate = $this->input->get('emirate');
if(!$country) return false;
$cities = $this->listings_model->get_activepair_cities(array('country_id'=>$country),'*','name asc');
$html = '<select name="emirate" id="emirate" class="form-control select2 required" onchange="oemirate(this);">';
$html .= ($emirate <1)? '<option value="">Select Emirate</option>':'';
foreach($cities as $city):
$html .= '<option value="'.$city['id'].'" '.($city['id'] == $emirate ? 'selected="selected"' : '').'>'.$city['name'].'</option>';
endforeach;
$html .= '<option value="Other">Other</option> </select><input type="text" id="other_emirate" name="other_emirate" class="form-control" style="display: none;" />';
echo json_encode(array('result'=>$html));
}
Now currently I'm working on edit page where it should initially show what value the user had selected while adding the entry. As of now the functionality of the second select works fine as intended as it changes its options when the 1st select data is changed and also gives the correct value in database when update is pressed.
Now the only problem here I have is that initially when loading into the page, it doesn't show anything in the second select box even though there is a value for it in the database. I performed a console.log(obj); in getcities(obj) and initially it returned undefined and everytime I change country, it gives a value in my log.
Related
https://i.stack.imgur.com/2O2Ug.png
when i change course name first row change only that row parent topic
how to do this please give advice
first course name select box code
<select class="form-control select2" onChange="getval(this.value)"; id="course_id1" name="course_id[]" data-live-search="true" >
<option value="" selected="selected"> Select Course Name</option>
<?php
$sql = "SELECT * from course_master";
$result = $connect->query($sql);
while($row_pt = $result->fetch_array())
{
?>
<option value="<?php echo $row_pt['course_id']; ?>" ><?php echo $row_pt['course_name']; ?></option>
<?php
}
?>
</select >
second select box when i select course name from drop down change that row parent id
<select class="form-control select2" id="parent_id" name="parent_id[]" data-live-search="true" ></select>
call function on change in course name
function getval(val)
{
$.ajax({
type: "POST",
url: "get.php",
data: {parent_id:val,syllabus_id:syllabus_id},
success: function(data)
{
$("#parent_id").html(data);
}
});
}
get.php
<?php
include('connection/core.php');
if(isset($_SESSION['userId']))
{
if (!empty($_POST["parent_id"]))
{
$query_sql = "SELECT syllabus_id,topic_name FROM syllabus WHERE syllabus_id!='". $_POST["syllabus_id"]."' AND course_id ='" .$_POST["parent_id"] ."'";
$results = $connect->query($query_sql);
echo $query_sql;
?>
<option value="0" selected> Parent </option>
<?php
foreach ($results as $p)
{
?>
<option value="<?php echo $p["syllabus_id"]; ?>"><?php echo $p["topic_name"]; ?></option>
<?php
}
}
}
?>
Add below code for your first row.
For example.
<select class="form-control select2 selectCourse" data-id="1" id="course_id_1" name="course_id_1[]" data-live-search="true" >
And for your parent topic name add as below.
<select class="form-control select2" id="parent_id_1" name="parent_id_1[]" data-live-search="true"></select>
Now when you are adding new dynamic row in your HTML then add selectCourse as class name in your select box of course name AND data-id="1" for each dynamically added row.
For example.
For course name add as below.
<select class="form-control select2 selectCourse" data-id="2" id="course_id_2" name="course_id_2[]" data-live-search="true" >
For parent topic name add as below.
<select class="form-control select2" id="parent_id_2" name="parent_id_2[]" data-live-search="true"></select>
In your script add code as below.
<script type="text/javascript">
$(document).on('change', '.selectCourse', function(){
var course_id = $(this).attr('data-id');
var val = $(this).find(":selected").val();
var syllabus_id = 1;
$.ajax({
type: "POST",
url: "get.php",
data: {parent_id:val,syllabus_id:syllabus_id},
success: function(data)
{
$("#parent_id_" + course_id).html(data);
}
});
});
</script>
I am not sure the title is explained perfectly.
I have 2 select tags and both select tags data are coming from the same table, in
The fist select tag - I am fetching data from the database which stores location name => This works perfectly and I have 3 locations name in the database.
<select name="location" class="form-label" id="location" required>
<option value="">Select Dojo Location</option>
<?php foreach ($location as $row): ?>
<option value="<?php echo $row->id; ?>"><?php echo $row->location; ?></option>
<?php endforeach; ?>
</select>
Image for first select tag
The second select tag - I am fetching prices from different columns of the same table but it shows every price from different locations.
<select name="month" class="form-label" id="month" required>
<option value="">Select Fees Period</option>
<?php foreach ($location as $row1): ?>
<option value="<?php echo $row1->admission_fee_1; ?>">Monthly</option>
<option value="<?php echo $row1->admission_fee_1; ?>">Quarterly</option>
<option value="<?php echo $row1->admission_fee_6; ?>">Half Yearly</option>
<option value="<?php echo $row1->admission_fee_12; ?>">Annually</option>
<?php endforeach; ?>
<?php endif; ?>
Image for second select tag
Image for table data
What I am trying to do is, when user select location in 1 select tag, so it only shows the prices of that selected location from database in second select tag.
This is what I am getting in the result
But I do not succeed yet, any solution is helpful or is there any other way to do this or am I doing it wrong.
Thanks in advance.
You have to use JavaScript and onChange method. It was resolved manytimes, e.g. how to change a selections options based on another select option selected?
You need to make some ajax call.
On Selection of first location tag; you can make jQuery Ajax call and get prices of that selected location only. In Ajax response you can receive HTML of second select tag and replace with current one.
Let me know if you need further explanation.
You need fetch the data dinamically.
Something like this
$( "#location" ).change(function() {
// this.value is your ID
$.post('/endpoint/fetch-details/' + this.value)
.done(function(data) {
// load data into another SELECT
})
.fail(function() {
alert( "error" );
})
});
On Codeigniter you could have a controller method (/endpoint/fetch-details/) that returns a JSON object.
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 am banging my head against a wall with this now so any help will go a long way with this one.
I am trying to get some data from a drop down list and update a database with the data selected.
This is my drop down list:
<form method="post" data-remote="true">
<select class="selectpicker" data-live-search="true" name="status[]">
<?php while($test3 = sqlsrv_fetch_array($test2, SQLSRV_FETCH_ASSOC)) : ?>
<option data-tokens="<?php echo $test3['Name']; ?>" value="<?php echo $test3['Name']; ?>">
</option
<?php endwhile; ?>
</select>
View Area
This is my ajax:
$(document).on('click', '#sim-area', function() {
$.ajax({
type: "POST",
url: 'sim-area.php',
data: {changeStatus: status},
success: function() {
"area switched"
}
});
});
and this is my page that is updating the databse (sim-area.php):
<?php
$userID = $user['userID'];
$selectedArea = $_GET['changeStatus'];
$queryAreaName = "
SELECT UserID, Name, U_NB, U_RTN
FROM Table
WHERE UserID = '$userID' AND Name = '$selectedArea'";
$getAreaname = sqlsrv_query($sapconn2, $queryAreaName);
$areaSwitch = sqlsrv_fetch_array($getAreaname, SQLSRV_FETCH_ASSOC);
$areaNB = $test2['U_NB'];
$areaRTN = $test2['U_RTN'];
//UPDATE TABLE
?>
No matter what I try I get an undefined error, I have changed it to hard code the values and in inserts fine, so I know everything is working fine, It just isn't passing the data through
Looks you are not passing data correctly to ajax call.
Below is updated code for dropdown (changed name of select and added id attribute):
<form method="post" data-remote="true">
<select class="selectpicker" data-live-search="true" name="status" id="changeStatus">
<?php while($test3 = sqlsrv_fetch_array($test2, SQLSRV_FETCH_ASSOC)) : ?>
<option data-tokens="<?php echo $test3['Name']; ?>" value="<?php echo $test3['Name']; ?>">
</option
<?php endwhile; ?>
</select>
Updated code for jquery (changed code for passing value of data):
$(document).on('click', '#sim-area', function() {
$.ajax({
type: "POST",
url: 'sim-area.php',
data: {changeStatus: $('#changeStatus').val()},
success: function() {
"area switched"
}
});
});
I have two dropdowns: state and city. Both are in the same form. The goal is to somehow save the selection without clicking submit button so it could be used as a criteria to display selections of cities in the second dropdown.
For example: When california is chosen in the first dropdown, second dropdwon displays all the cities in California.
Code:
<?php $db= DB::table('states_table')->get(); ?>
<select class="form-control input-md" name="state">
<option value="" disabled selected>Choose the state</option>
<?php foreach ($db as $data) { ?>
<option value="<?php echo $data->city; ?>">
<?php echo $data->city;?>
</option><?php
}?>
</select>
just use ajax :
$('#form').on('change','select[name="state"]', function() {
var province = $('select[name=state]').val();
$.ajax({
url: './get_city.php',
method: 'post',
data: {"state": state},
success: function (data) {
$('select[name=city]').html(data);
}
})
});
and in the get_city.php connect to db , get the cities and return them on tags
$('#state_field_id').click(function(){
var state=document.getElementById('state_field_name').options[document.getElementById('state_field_name').selectedIndex].text;
});
you will get selected value
I am trying to create a dependent dynamic drop down box on three input fields. At the moment the each input field is getting their data from their individual tables called tour_type, countries and destination. This is the form:
<label>Tour Type </label>
<select id="tourtype" name="tourtype" required>
<option value="" selected="selected">--Select--</option>
<?php
$sql=mysql_query("Select tour_type_id,tour_name from tour_type");
while($row=mysql_fetch_array($sql))
{
$tour_type_id=$row['tour_type_id'];
$name=$row['tour_name'];
echo "<option value='$tour_type_id'>$name</option>";
}
?>
</select>
<label>Country </label>
<select id="country" name="country" class="country" required>
<option value="" selected="selected">-- Select --</option>
<?php
$sql=mysql_query("SELECT * FROM `countries` where `tour_type_id` = ?"); //what should i put in here?
while($row=mysql_fetch_array($sql))
{
$cid=$row['countries_id'];
$name=$row['countries_name'];
echo "<option value='$cid'>".$name."</option>";
}
?>
</select>
<label>Destination </label>
<select id="destination" name="destination" class="destination" required>
<option value="" selected="selected">-- Select --</option>
<?php
$sql=mysql_query("SELECT * FROM `destination` where `countries_id` = ?");//what should i put in here?
while($row=mysql_fetch_array($sql))
{
$destination_id=$row['destination_id'];
$name=$row['destination_name'];
echo "<option value='$destination_id'>".$name."</option>";
}
?>
</select>
This is the javascript at the top of the form
<script type="text/javascript">
$(document).ready(function()
{
$(".country").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$(".destination").html(html);
}
});
});
});
</script>
Finally these are the 3 tables i.e. tour_type, countries and destination respectively:
Can anyone help me on this?
How do I make each drop down box dependable on each other? For e.g. If i select Culture on the 1st drop down, then only Holland and Belgium should show in the 2nd drop down. So now if i select Holland from 2nd drop down, then Amsterdam should show in the 3rd drop down.
This is the ajax.php which i am not too sure if it is right.
<?php
include('../config.php');
if($_POST['']) //what should i put in here?
{
$id=$_POST['']; //what should i put in here?
$sql=mysql_query //this is where i do not know what to put;
while($row=mysql_fetch_array($sql))
{
//And what should i be placing here
}
}
?>
This is what the web front end form looks like after implementing the code provided by dianuj. I still can not select the 2nd and 3rd drop down boxes:
So first you have the tour type select box. So just move the code for fetching countries based on tour type to ajax.php. Also include one more parameter to distinguish which type(tour type,country etc) you are posting. so you will get the id and based on the type parameter you can fetch from different tables. Then create a selectbox HTML snippet and output it. This will return for the AJAX call and you can insert the HTML.
You can use ajax get here and can use the shorthand version like
$.get('ajax,php?id=idhere&type=country', function(data) {
$('#country_result').html(data);
});
Where result is the id of div to which the select box has to be inserted.
So the HTML part will be like
<div id="country_result"></div> //Country select box goes here
<div id="destination_result"></div> //Country select box goes here
The simplest approach is to fetch select options from the server when the selections change, like so:
$('#tour_type').change(function() {
// load country options
});
$('#country').change(function() {
// load destination options
});
The server should simply return a snippet of HTML containing the available options for country and destination.
here you go you have to fetch the options from the ajax.php do not place the query in second dropdown
<label>Tour Type </label>
<select id="tourtype" name="tourtype" required>
<option value="" >--Select--</option>
<?php
$sql=mysql_query("Select tour_type_id,tour_name from tour_type");
while($row=mysql_fetch_array($sql))
{
$tour_type_id=$row['tour_type_id'];
$name=$row['tour_name'];
echo "<option value='$tour_type_id'>$name</option>";
}
?>
</select>
<label>Country </label>
<select id="country" name="country" class="country" required>
<option value="">-- Select --</option>
</select>
<label>Destination </label>
<select id="destination" name="destination" class="destination" required>
<option value="">-- Select --</option>
</select>
initially country and destination drop down should be empty here your js goes
$('#tour_type').change(function() {
var id=$(this).val();
$.ajax
({
type: "POST",
url: "ajax.php",
data: "&id="+id+"&get_countries=1",
success: function(html)
{
$("#country").append(html);
}
});
});
$('#country').change(function() {
var id=$(this).val();
$.ajax
({
type: "POST",
url: "ajax.php",
data: "&id="+id+"&get_destination=1",
success: function(html)
{
$("#destination").append(html);
}
});
});
And your ajax.php
<?php
if($_REQUEST['get_countries']){
$sql=mysql_query("SELECT * FROM `countries` where `tour_type_id`=".$_REQUEST['id']);
$countries="";
while($row=mysql_fetch_array($sql))
{
$cid=$row['countries_id'];
$name=$row['countries_name'];
$countries.= "<option value='".$cid."'>".$name."</option>";
}
echo $countries;
}elseif($_REQUEST['get_destination']){
$destination="";
$sql=mysql_query("SELECT * FROM `destination` where `country_id` =".$_REQUEST['id'])
while($row=mysql_fetch_array($sql))
{
$destination_id=$row['destination_id'];
$name=$row['destination_name'];
$destination.= "<option value='".$destination_id."'>".$name."</option>";
}
echo $destination;
}
?>
Hope it works fine
<label>Tour Type </label>
<select id="tourtype" name="tourtype" required onchange="get_country($(this).val())">
<option value="" selected="selected">--Select--</option>
<?php
$sql=mysql_query("Select tour_type_id,tour_name from tour_type");
while($row=mysql_fetch_array($sql))
{
$tour_type_id=$row['tour_type_id'];
$name=$row['tour_name'];
echo "<option value='$tour_type_id'>$name</option>";
}
?>
</select>
<label>Country </label>
<select id="country" name="country" class="country" required onchange="get_destination($(this).val())">
<option value="" selected="selected">-- Select --</option>
</select>
<label>Destination </label>
<select id="destination" name="destination" class="destination" required>
<option value="" selected="selected">-- Select --</option>
</select>
<script>
function get_country(tour_type)
{
$.post("ajax.php",{get_country:tour_type},function(data){
var data_array = data.split(";");
var number_of_name = data_array.length-1;
var value;
var text;
var opt;
var temp_array;
for(var i=0; i<number_of_name; i++)
{
value=temp_array[i];
//alert(value);
text=temp_array[i];
opt = new Option(text,value);
$('#country').append(opt);
$(opt).text(text);
}
$("#country").prop("disabled", false);
});
}
//same way script for getting destination
</script>
// now in ajax file
if(isset($_POST["get_country"]))
{
$tour_type = str_replace("'","",stripslashes(htmlentities(strip_tags($_POST["get_country"]))));
$country_select = mysql_query("select * from country where tour_type_id = '$tour_type'");
$country="";
while($country_row = mysql_fetch_array($country_select))
{
$country = $country.$country_row["country"].";";
}
echo $country;
}
// same way ajax for destination