I have this dependent dropdown working initially, but after the second selection the values of the first selection do not go away. Instead, the new values are just mixed with the previous values. I'm not familiar with jQuery but I need to finish this one as soon as possible.
first dropdown
<select class="form-control" name = "PROV_ID" id = "PROV_ID">
<option></option>
<?php foreach ($content as $cs) {?>
<option value="<?php echo $cs->PROV_ID; ?>"><?php echo $cs->PROVINCE; ?></option>
<?php } ?>
</select>
second dropdown
<select name = 'CT_ID' id = 'CT_ID'>
<option value="">-- Select Type --</option>
</select>
jquery
<script>
jQuery(document).ready(function(){
$("#PROV_ID").change(function() {
var PROVID = {"PROVID" : $('#PROV_ID').val()};
console.log(PROVID);
$.ajax({
type: "POST",
data: PROVID,
url: "<?php base_url(); ?>Employees/dependent_dropdown",
success: function(data){
$.each(data, function(i, data){
$('#CT_ID').append("<option value='"+data.CT_ID+"'>"+data.CITY+"</option>");
});
}
});
});
});
</script>
I want to refresh the value of the second dropdown whenever I select a new option on the first dropdown.
Clear the existing options before appending:
success: function(data){
var select = $('#CT_ID');
select.empty();
$.each(data, function(i, option){
select.append("<option value='"+option.CT_ID+"'>"+option.CITY+"</option>");
});
}
This is because you are using append to add HTML to the select element. I would suggest using jQuery's html to set the HTML of the select (which will clear any existing option elements). The added benefit here is that you are only doing one DOM manipulation, as opposed to one per option.
success: function(data){
var $select = $('#CT_ID'),
html = '';
$.each(data, function(i, option) {
html += "<option value='"+option.CT_ID+"'>"+option.CITY+"</option>";
});
$select.html(html);
}
Related
I'm trying to re-use the same code on several web pages to tidy up the code, especially when the same AJAX response in used once/few times on the page.
The response is a list of <option> to be placed into <select>.
On a NEW ENTRY to database page load, I want the <select> to be filled with correct <options>.
On an UPDATE to database page load, I want the <select> to be initially filled with selected <option selected>, but when .change is triggered, the cascading <select> must update accordingly.
Everything worked as expected, until I've decided to reuse the same code (response from Ajax) instead of having separate php syntax inside each <select>.
Now, when the page is loading the <select> values in all div's gets overwritten by the value from the last one.
Any Idea on how to accomplish this?
here is my code so far:
webpage.php
<div class="form-group">
<div class="col-xs-2"><input type="hidden" class="deptList_value" value="<?php echo $row['fDeptFK'];?>">
<select class="form-control deptList" name="deptFK" onchange="getId(this.value);" required>
</select>
</div>
<div class="col-xs-2"><input type="" class="areaList_value" value="<?php echo $row['PK'].'-'.$row['fDeptFK'].'-'.$row['fAreaFK'];?>">
<select class="form-control areaList" name="areaFK" required>
</select>
</div>
</div>
jquery:
$(document).ready(function(){
$(".deptList_value").each(function() {
var deptPK = $(this).val();
//alert(deptPK);
$.ajax({
url:"../GetData_DropDown/getdataDeptQA.php",
method:"POST",
data:{DeptNo:deptPK},
dataType:"text",
success:function(data)
{
$('.deptList').html(data);
}
});
});
$(".areaList_value").each(function() {
var arr = $(this).val().split('-');
var idPK = arr[0];
var deptPK = arr[1];
var areaPK =arr[2];
$.ajax({
url:"../GetData_DropDown/getdataAreaQA.php",
method:"POST",
data:{AreaNo:areaPK,DeptNo:deptPK},
dataType:"text",
success:function(data)
{
$('.areaList').html(data);
}
});
});
$('.deptList').change(function(){
var deptPK = $(this).val();
$.ajax({
url:"../GetData_DropDown/getdataAreaQA.php",
method:"POST",
data:{DeptNo:deptPK},
dataType:"text",
success:function(data)
{
$('.areaList').html(data);
}
});
});
getdataAreaQA.php
$output = '<option value=""></option>';
foreach($conn->query("EXEC [qa].[getQA_area_list] ".$_POST["DeptNo"]) as $rowA) {
if ($rowA['PK']==$_POST['AreaNo']) {
$output .= '<option value="'.$rowA['PK'].'" data-AP24FKvalue="'.$rowA['AP24FK'].'" selected>'.$rowA['Name'].'</option>';
} else {
$output .= '<option value="'.$rowA['PK'].'" data-AP24FKvalue="'.$rowA['AP24FK'].'">'.$rowA['Name'].'</option>';
}
}
echo $output;
EDIT
Not tested but this should work on a page with single row from database. The issue is with paginated pages with multiple rows on one page.
I propose you simplify a little bit more, and use specialized unique id in combination with your class handlers.
Lets first start by adjusting rows output from your loop:
<?php
$idx = 0;
/* your foreach/for/while loop */ {
$idx++;// just ensuring a unique value to utilize
?>
<div class="form-group">
<div class="col-xs-2">
<select id="dept_<?php echo $idx;?>"
data-dept="<?php echo $row['fDeptFK'];?>"
data-idx="<?php echo $idx;?>"
class="form-control deptList" name="deptFK" required>
</select>
</div>
<div class="col-xs-2">
<select id="area_<?php echo $idx;?>"
data-dept="<?php echo $row['fDeptFK'];?>"
data-area="<?php echo $row['fAreaFK'];?>"
data-idx="<?php echo $idx;?>"
class="form-control areaList" name="areaFK" required>
</select>
</div>
</div>
<?php }?>
No need for hidden inputs. The data-vars will contain all that you need. Note that each id should be unique per row output.
Now some slight adjustments to the jquery:
$(document).ready(function(){
$(".deptList").each(function() {
var idx = $(this).data('idx');// the unique row id
var dept = $(this).data('dept');
$.ajax({
url:"../GetData_DropDown/getdataDeptQA.php",
method:"POST",
data:{DeptNo: dept},
dataType:"html",
success:function(data)
{
$("#dept_"+idx).html(data);// targets unique id
}
});
});
$(".areaList").each(function() {
var idx = $(this).data('idx');
var dept = $(this).data('dept');
var area = $(this).data('area');
$.ajax({
url:"../GetData_DropDown/getdataAreaQA.php",
method:"POST",
data:{AreaNo: area, DeptNo: dept},
dataType:"html",
success:function(data)
{
$("#area_"+idx).html(data);
}
});
});
$('.deptList').change(function(){
var idx = $(this).data('idx');
var dept = $(this).val();// using .val not .data
$.ajax({
url:"../GetData_DropDown/getdataAreaQA.php",
method:"POST",
data:{DeptNo: dept},
dataType:"html",
success:function(data)
{
$("#area_"+idx).html(data);// targets area select
// you may want to update the area selects data too:
$("#area_"+idx).data('dept', dept);
}
});
});
});
By targeting using the row idx value, you can ensure which sub select options will be changed out. All the data-vars contain values for what you need to initially populate the select options.
Important Note
As we discovered through comments... if you try to use capitals in a data-varNAME, it will result in undefined when accessing it with the .data() jquery method. So instead, make sure the naming of the data-varname has no caps and it will be ok.
I want to populate a dropdown (AJAX) when I click on the dropdown.
I have a dropdown categories and a button Add categories
When I open the page the first time, I can see my categories inside the dropdown.
If I want to include another categories, I click on Add categories and I insert my new categories.
After, if I click on the dropdown, I must see my new categories.
How to do that ?
I don't know exactly how to create that.
Thank you
my_ajax_file.php
$Qcheck = $OSCOM_Db->prepare('select categories_id as id,
categories_name as name
from :table_categories');
$Qcheck->execute();
$list = $Qcheck->rowCount();
if ($list > 0) {
$array = [];
while ($value = $Qcheck->fetch() ) {
$array[] = $value;
}
# JSON-encode the response
$json_response = json_encode($array); //Return the JSON Array
# Return the response
echo $json_response;
HTML code
<script type="text/javascript">
function Mycategory_id() {
$("#myAjax").on('click', function(){
$.ajax({
url: 'http://www.my_ajax_file.php',
dataType: 'json',
success: function(data){
//data returned from php
}
});
});
}
</script>
<select name="category_id" id="Mycategory_id" class="form-control">
<option value="0" selected="selected">Haut</option>
<option value="23">Panneaux Signalétique</option>
<option value="20">Signalétique Camping</option>
<option value="22"> Barrières</option>
<option value="21"> Entrée</option>
</select>
<input type="hidden" name="current_category_id" value="0" /></div>
You need to update the select element with new options.
<script type="text/javascript">
function Mycategory_id() {
$("#myAjax").on('click', function(){
$.ajax({
url: 'http://www.my_ajax_file.php',
dataType: 'json',
success: function(data){
//data returned from php
var options_html = '';
for(index in data){
var category_id = data[index]['categories_id'];
var category_name = data[index]['categories_name'];
options_html += '<option value="'+category_id+'">' + category_name + '</option>';
}
$('#category_id').html(options_html);
}
});
)};
</script>
To make rendering easy, you can use mustache.js
I have a problem putting Onchange() on a ajax returned html on my form.
Basically I have clients listed in a select.
<select name="company" id="company">
<?php
$sqlget1 = "SELECT * FROM clients WHERE 1=1 ORDER BY company ASC;";
$resget1 = mysql_query($sqlget1);
while($row1 = mysql_fetch_array($resget1)) {
?>
<option value="<?php echo $row1['id']; ?>"><?php echo $row1['company']; ?></option>
<?php
}
?>
</select>
And when some one selects a client, im using Ajax to fetch projects that are assigned to that client.
$('#company').change(function() {
var selectedProject = $("#company option:selected").val();
$.ajax({
type: "POST",
url: "get_projects.php",
data: { projects : selectedProject }
}).done(function(data){
$("#response").html(data);
});
});
It gets returned back to
<div id="response"></div>
The code for get_projects.php is
<?php
include('inc.php');
if(isset($_POST["projects"])) {
$projects = $_POST["projects"];
$sqlget2 = "SELECT * FROM projects WHERE cid=\"$projects\" ORDER BY pname ASC;";
$resget2 = mysql_query($sqlget2);
echo '<select name="project" id="project" class="select2 form-control">';
echo '<option value="">-- Select a project --</option>';
while($row2 = mysql_fetch_array($resget2)) {
?>
<option value="<?php echo $row2['id']; ?>" pstatus="<?php echo $row2['pstatus']; ?>" ptype="<?php echo $row2['ptype']; ?>"><?php echo $row2['pname']; ?></option>
<?php
}
echo '</select>';
}
?>
Now when i use on change function on the returned html from ajax it is not working.
I tried to see the source code and found out that it is not there atall. It only shows the <div id="response"></div>
But i can see the result on the form but cant see the source in the source code.
Hence i thought that's why the Onchange() is not working for <select name="project" id="project" class="select2 form-control"> because it is not showing.
I see, the data which is return from Ajax is object
You should parse it to get the raw content an set into DIV
When you are dynamically adding mark up to the page the javascript doesn't know about the controls you have added through php.
Try finding the newly added control like this:
var select = document.getElementById('project');
Then you should be able to fire your on change method
Not tested, but it should work
<?php
include('inc.php');
if(isset($_POST["projects"]))
{
$projects = $_POST["projects"];
$varOut = "";
$sqlget2 = "SELECT * FROM projects WHERE cid=\"$projects\" ORDER BY pname ASC;";
$resget2 = mysql_query($sqlget2);
$varOut .= '<select name="project" id="project" class="select2 form-control">';
$varOut.= '<option value="">-- Select a project --</option>';
while($row2 = mysql_fetch_array($resget2))
{
$varOut.= "<option value=" . $row2['id'] . " pstatus=". $row2['pstatus']. ">ptype=".$row2['ptype']."><".$row2['pname']."></option>";
}
$varOut.= '</select>';
}
echo $varOut;
?>
I've finally solved the issue.
Basicall i just pasted the Onclick() script for '#projects' inside the get_projects.php file.
So now every time when it comes from ajax it also brings the javascript as well.
When you use ajax, you add a piece of html later to the DOM (browsers view), because you use .change the onchange is only added to the '#company' elements wich already exist in the browser.
You need to bind the onchange after you appended the html. for example:
$('#company').change(function() {
onCompanyChange()
});
function onCompanyChange(){
var selectedProject = $("#company option:selected").val();
$.ajax({
type: "POST",
url: "get_projects.php",
data: { projects : selectedProject }
}).done(function(data){
$("#response").html(data);
$('#company').change(function() {
onCompanyChange()
});
});
}
OR
You can also use an on change, on change does work with elements added later to to the dom. so this code works with elements wich already exists and new added elements with for example ajax
$("#company").on("change",function(){
console.log("change");
});
Try below code. Hope this works fine.
$(document).ready(function() {
$(document).on('change', '#company', function() {
var selectedProject = $("#company option:selected").val();
$.ajax({
type: "POST",
url: "get_projects.php",
data: { projects : selectedProject }
}).done(function(data){
$("#response").html(data);
});
});
});
I have this dependent dropdown function where I have a dropdown and another one depending on it,
here is the HTML
<select class="form-control" name = "PROV_ID" id = "PROV_ID">
<option></option>
<?php foreach ($content2 as $cs) {?>
<option value="<?php echo $cs->PROV_ID; ?>"><?php echo $cs->PROVINCE; ?></option>
<?php } ?>
</select>
<select class="form-control" name = 'CT_ID' id = 'CT_ID'>
<option value=""></option>
</select>
and here is the javascript
jQuery(document).ready(function(){
$("#PROV_ID").change(function() {
var PROVID = {"PROVID" : $('#PROV_ID').val()};
console.log(PROVID);
$.ajax({
type: "POST",
data: PROVID,
url: "<?php base_url(); ?>Employees/dependent_dropdown/",
success: function(data){
var select = $('#CT_ID');
select.html('');
$.each(data, function(i, option){
select.append("<option value='"+option.CT_ID+"'>"+option.CITY+"</option>");
});
}
});
});
});
now I want to have one like this, but I wanted to have selected values for the first two dropdowns before the dependent one shows the values.
e.g.
first dropdown -->select a value
second dropdown -->selects a value
dependent dropdown --> gives values according to first and second dropdown.
example: select * from thistable where column1 = 'firstdropdownvalue' and column2 = 'seconddropdownvalue'
then the dropdown values would be the result.
jQuery(document).ready(function(){
$("#CT_ID").change(function() {
var PROVID_two = {"PROVID" : $('#PROV_ID').val(), "CT_ID" : $('#CT_ID').val()};
console.log(PROVID);
$.ajax({
type: "POST",
data: PROVID_two,
url: "<?php base_url(); ?>Employees/dependent_dropdown2/",
success: function(data){
var select = $('#PROVID_two');
select.html('');
$.each(data, function(i, option){
select.append("<option value='"+option.CT_IDnew+"'>"+option.CITYnew+"</option>");
});
}
});
});
});
You can try like this. Pass two selected values. Hope you understood
I am creating a category system where users can select category from DB and after they select it creates another select box with subcategory of that category.
So, my question is how can I do it the best way?
BTW I am using Laravel Framework and first category is simple
<select>
#foreach(Category::all() as $k)
<option value="{{ $k['id'] }}">{{ $k['name'] }}</option>
#endforeach
</select>
But what should I do after they pick a category? Is it better to do the AJAX call to send the ID of picked category and returns the subcategory or what?
I need the best and professional way to do this.
In my Database I have
ID, name, parent
Use ajax, after selecting the category send the ajax request and to do this you need to use change event on your select, for example:
// Assumed category is id of the select
$('#category').on('change', function(){
var id = $(this).val();
$.getJSON("subcategory/" + id , function(data){
// Assumed subcategory is id of another select
var subcat = $('#subcategory').empty();
$.each(data, function(k, v){
var option = $('<option/>', {id:k, value});
subcat.append(option);
});
});
});
On the server side, create a route like this (You may use a controller and Eloquent):
Route('subcategory/{id}', function($id){
// Get the data from database according to the id
// Build an array as: id => value and then return
return Response::json($subcat);
});
Populate a dropdown on selecting an option from another dropdown Laravel
This might surely help you. Otherwise ask if you do not understand
select_cat.php
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".category").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "select_subcat.php",
data: dataString,
cache: false,
success: function(html)
{
$(".subcat").html(html);
}
});
});
});
</script>
Category :
<select name="category" class="category">
<option selected="selected">--Select Category--</option>
<?php
include('databasefile');
mysql_connect($server,$username,$password)or die(mysql_error());
mysql_select_db($database)or die(mysql_error());
$sql=mysql_query("select cat_name from category order by cat_name");
while($row=mysql_fetch_array($sql))
{
$cname=$row['cat_name'];
echo '<option value="'.$cname.'">'.$cname.'</option>';
} ?>
</select> <br/><br/>
SubCategory :
<select name="subcat" class="subcat">
<option selected="selected">--Select SubCat--</option>
</select>
2.select_subcat.php
<?php
include('databasefile);
mysql_connect($server,$username,$password)or die(mysql_error());
mysql_select_db($database)or die(mysql_error());
if($_POST['id'])
{
$id=$_POST['id'];
$sql=mysql_query("select s_name from subcat_l1 where cat_name='$id'");
while($row=mysql_fetch_array($sql))
{
$sname=$row['s_name'];
echo '<option value="'.$sname.'">'.$sname.'</option>';
}
}
?>
SubCategory :
<select name="subcat" class="subcat">
<option selected="selected">--Select SubCat--</option>
</select>