I use an AJAX to display my categories. My problem is when I select a category, the dropdown come back always at this initial position
For example, if I click "Panneaux lumineux", the dropdown go back to "Select your categorie" automatically. in this case "Panneaux lumineux" is not selected.
Tk
<div class="col-md-5">
<script type="text/javascript">
jQuery(document).ready(function() {
$("#myAjax").on('click', function () {
$.ajax({
url: 'http://Admin/products_categories_ajax.php',
dataType: 'json',
success: function (data) {
//data returned from php
var options_html = '<option value="">-- Select your categorie --</option>';
for (index in data) {
var category_id = data[index]['id'];
var category_name = data[index]['text'];
options_html += '<option value="' + category_id + '">' + category_name + '</option>';
}
$('#category_id').html(options_html);
}
});
});
})
</script>
<div id="myAjax">
<select name="move_to_category_id" id="category_id">
<option value="">-- Select your categorie --</option>
<option value="0">Haut</option>
<option value="25">Panneaux lumineux</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 name="current_category_id" value="20" type="hidden" />
</div>
</div>
The issue you have occurs, because your dropdown list is replaced with a new one when you click on the dropdown. Even if the dropdown is visually the same, it isn't in the DOM.
To solve it, you need to save the selected category ID and select it after the dropdown has been replaced.
<div class="col-md-5">
<script type="text/javascript">
jQuery(document).ready(function() {
$("#myAjax").on('click', function () {
var selectedCategory = $('select#category_id').val();
$.ajax({
url: 'http://Admin/products_categories_ajax.php',
dataType: 'json',
success: function (data) {
//data returned from php
var options_html = '<option value="">-- Select your categorie --</option>';
for (var index in data) {
var category_id = data[index]['id'];
var category_name = data[index]['text'];
options_html += '<option value="' + category_id + '"' + (category_id == selectedCategory ? ' selected' : '') + '>' + category_name + '</option>';
}
$('#category_id').html(options_html);
}
});
});
})
</script>
<div id="myAjax">
<select name="move_to_category_id" id="category_id">
<option value="">-- Select your categorie --</option>
<option value="0">Haut</option>
<option value="25">Panneaux lumineux</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 name="current_category_id" value="20" type="hidden">
</div>
</div>
Above the
$.ajax function call
add
var selectedOptionVal = $('#category_id').val();
to save the value you selected.
then use that value to make the correct option selected when you recreate the html. So then try changing
for (index in data) {
var category_id = data[index]['id'];
var category_name = data[index]['text'];
options_html += '<option value="' + category_id + '">' + category_name + '</option>';
}
to
for (var index in data) {
var category_id = data[index]['id'];
var category_name = data[index]['text'];
var selectedString = category_id == selectedOptionVal ? ' selected="selected"' : '';
options_html += '<option value="' + category_id + '"' + selectedString + '>' + category_name + '</option>';
}
Related
I need to add multiple dropdowns to my project and it also needs a dependent multiple dropdowns
The existing dropdown category should be changed to multiple dropdowns
Automatically they select values in its dependent subcategory multiple dropdowns it its possible ?
Current Single Choice Dependent Dropdown How To Make Multiple Choose Dependent Dropdown?
please help me
view page
<label for="category_id"><?php echo get_phrase('category'); ?> <span
class="text-danger">*</span></label>
<select class="form-control selectpicker" name="category_id" id="category_id" required multiple>
<option value="" hidden><?php echo get_phrase('select category'); ?></option>
<?php
$roles = $this->db->get('category_table')->result_array();
foreach($roles as $row):
?>
<option value="<?php echo $row['category_id'];?>">
<?php echo $row['category_name'];?>
</option>
<?php
endforeach;
?>
</select>
<label for="idsubcategory"><?php echo get_phrase('Sub_category'); ?>
<span class="text-danger"></span> </label>
<select class="form-control" name="idsubcategory" id="idsubcategory"
placeholder="subcategory" multiple>
<option value="" hidden><?php echo get_phrase('select subcategory'); ?></option>
<?php
$roles = $this->db->get('sub_category')->result_array();
foreach($roles as $row):
?>
<option value="<?php echo $row['idsubcategory'];?>">
<?php echo $row['subcategory_name'];?>
</option>
<?php
endforeach;
?>
</select>
ajax
$(document).ready(function()
{
$('#category_id').change(function() {
var category_id = $(this).val();
$.ajax({
url: "<?php echo site_url('admin/get_sub_category');?>",
method: "POST",
data: {
category_id: category_id
},
async: true,
dataType: 'json',
success: function(data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
html += '<option value=' + data[i].idsubcategory + '>' + data[i]
.subcategory_name + '</option>';
}
$('#idsubcategory').html(html);
}
});
return false;
});
});
controller
function get_sub_category(){
$category_id = $this->input->post('category_id',TRUE);
$data = $this->Crud_model->get_sub_category($category_id)->result();
echo json_encode($data);
}
model
function get_sub_category($category_id){
$query = $this->db->get_where('sub_category', array('category_id' => $category_id));
return $query;
}
<select id="select1">
<option value='opt1'>Option 1</option>
<option value='opt2'>Option 2</option>
<option value='opt3'>Option 3</option>
</select>
<select id="select2">
<select>
<select id="select3">
<select>
<script>
$('#select1').change(function() {
var category_id = $(this).val();
$.ajax({
url: "<?php echo site_url('controller/function_for_second_dropdown');?>",
method: "POST",
data: {
category_id: category_id
},
async: true,
dataType: 'json',
success: function(data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
html += '<option value=' + data[i].idsubcategory + '>' + data[i].your_option+ '</option>';
}
$('#select2').append(html);
}
});
$('#select2').change(function() {
var select2= $(this).val();
$.ajax({
url: "<?php echo site_url('controller/function_for_third_dropdown');?>",
method: "POST",
data: {
select2: select2
},
async: true,
dataType: 'json',
success: function(data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
html += '<option value=' + data[i].your_option + '>' + data[i].your_option+ '</option>';
}
$('#select2').append(html);
}
});
</script>
I am Using bootstrap multi select. I have two drop downs and both have datas with search feature.
what i am doing .. on change function on first drop down i want to change second drop down value using ajax.I have used rebuild too. But search feature value is not changing
<select class="selectpicker form-control multiselect" multiple="multiple" role="multiselect" data-live-search="true" id="sel1">
<option selected disabled> Class</option>
<option value="one">one</option>
<option value="two">two</option>
<option value=" three">three</option>
</select>
<select class="selectpicker form-control multiselect" multiple="multiple" role="multiselect" data-live-search="true" id="sel2">
<option selected disabled>Molecule</option>
<option value="100 student">100 student</option>
<option value="200 student">200 student</option>
<option value="300 student">300 student</option>
</select>
My ajax function
$("#sel1").change(function () {
$.ajax({
type: "POST",
url: "http://test.com/selectdropdown",
cache: false,
data: {
classval: val1
},
}).done(function (msg) {
var data = $.parseJSON(msg);
var options = '';
var tmp = [];
for (var i = 0; i < data.classdata.length; i++) {
var id = data['classdata'][i]['class_id'];
var name = data['classdata'][i]['noofstudent'];
options += '<option value=' + id + '>' + name + '</option>';
element = { "label": name, "value": id }
tmp.push(element);
}
$("#sel2").multiselect('dataprovider', tmp);
$('#sel2').multiselect('rebuild');
})
});
but drop down two data is not chaning.. if i use inspect element i can see the data
After lot of rnd . I have got solution. i have to refresh select picker too. hope this help to others
$('.selectpicker').selectpicker('refresh');
I have total 4 select boxes( e.g: 1) Car Make, 2) Car Model, 3) Manufacturing Year, 4) Body Type). I am able to populate the values to the 3rd select box i.e. Year but cant get the values for the last one. These data are fetched from the database table called carlist.
For Example: Select Car Make as Audi
Select Car Model as A4
Select Manufacturing Year 2009
But now in the 4th select options, I get all the Car body types as:
4WD
Van
Sedan
Wagon
Coupe
The result I want to fetch is only sedan.
I am also able to make a success call from Ajax and when I am alerting it, I am getting the required results, but I am not able to get the values in the select box.
My code:
index.blade.php
<select class="form-input select button-shadow dynamic" name="Make" id="Make" data-dependent='Model'>
#foreach($carLists as $carMake)
<option value="{{$carMake->Make}}">{{$carMake->Make}} </option>
#endforeach
</select>
</div>
<div class="form-wrap">
<select class="form-input select button-shadow dynamic" name="Model" id="Model" data-dependent='Year'>
<option value="">Select Make</option>
</select>
</div>
<div class="form-wrap">
<select class="form-input select button-shadow dynamic" name="Year" id="Year" data-dependent='Body'>
<option value="">Select Year</option>
</select>
</div>
<div class="form-wrap">
<select class="form-input select button-shadow dynamic" name="Body" id="Body">
<option value="">Select Body</option>
</select>
</div>
PagesController.php
function fetch(Request $request)
{
$select = $request->get('select');
$value = $request->get('value');
$dependent = $request->get('dependent');
$data = DB::table('carlists')
->where($select, $value)
->groupBy($dependent)
->get();
$output = '<option value="">Select '.ucfirst($dependent).'</option>';
foreach($data as $row)
{
$output .= '<option value="'.$row->$dependent.'">'.$row->$dependent.'</option>';
}
echo $output;
}
function fetchbody(Request $request)
{
$make = $request->get('make');
$model = $request->get('model');
$year = $request->get('year');
$dependent = $request->get('dependent');
$data = DB::select('Select Make, Model, Year, Body FROM carlists WHERE Make = "'.$make .'" AND Model = "'.$model .'" AND Year = "'.$year .'" GROUP by Body');
$output = '<option value="">Select '.ucfirst($dependent).'</option>';
foreach($data as $row)
{
$output .= '<option value="'.$row->$dependent.'">'.$row->$dependent.'</option>';
}
echo $output;
}
Route.php
Route::post('inc/sidebar/fetch', 'PagesController#fetch')->name('pagescontroller.fetch');
Route::post('car/make/body/fetch', 'PagesController#fetchbody')->name('bodycontroller.fetch');
javascript:
<script>
$('#Year').on('change', function(e){
var make = $('#Make').val();
var model = $('#Model').val();
var year = e.target.value;
var dependent = $(this).data('dependent');
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('bodycontroller.fetch') }}",
method:"POST",
data:{make:make, model:model, year:year, _token:_token, dependent:dependent},
success:function(result)
{
$('#'+dependent).html(result);
alert('Sucess: ' + make + ' ' + model + ' ' + year + result);
}
})
});
</script>
<script>
$(document).ready(function(){
$('.dynamic').change(function(){
if($(this).val() != '')
{
var select = $(this).attr("id");
var value = $(this).val();
var dependent = $(this).data('dependent');
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('pagescontroller.fetch') }}",
method:"POST",
data:{select:select, value:value, _token:_token, dependent:dependent},
success:function(result)
{
$('#'+dependent).html(result);
}
})
}
});
</script>
Not too sure how to fix this and display as options.
You can't get the value in select box because jquery onchange listener was set up before any value were appended into element, and it don't detect that option values were updated.
To do jquery onchange work as expected, you can remove event handler and add it again after populate your select box, but I don't recommend.
The better approach is use event.target to get data.
$('.dynamic').change(function(event){
const value = event.target.value
...
})
https://codepen.io/lc-brito/pen/dLMVaj
I have two tables in database: city and local_area
city :
id name
1 FSD
2 LHr
Local_area :
id city_id name
1 1 Kohnoor
2 1 samnabad
3 2 joharabad
4 2 amanabad
<select>
<option value="1">Fsd</option>
<option value="2">LHR</option>
</select>
I have a select box that allows to me to choose the city to display. When I select a city it should show a new HTML element showing all local_area for the given city.
I Have to do this using jQuery, after selection I want to store my record in database table.
<select id="ddCity">
<option value="-1"></option>
<option value="1">FSD</option>
<option value="2">LHr</option>
</select>
<div id="local_area_Grid"></div>
<script>
$(function(){
$("#ddCity").change(function(){
if($(this).val() != -1){
$.ajax({
url: "Server_address",
data:{cityId = $(this).val()},
success: function(data){
var _table = $("<table></table>");
for(var i = 0; i< data.length; i++){
$("<tr></tr>").append($("<td></td>").html("<label><input type='checkbox' value='data[i]' name='local_area'/>" + data[i] + "</label>")).appendTo(_table);
}
$("#local_area_Grid").html("").append(_table);
}
});
}
});
})
</script>
You should return an array from service
You need to use jQuery AJAX to "ask" a server for list of areas corresponding to the city. Or, may be, it would be better for you to load full list of all areas with page. For example:
<script language="JavaScript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<select id="city" name="city">
<option value="0">- Select -</option>
<option value="1">Fsd</option>
<option value="2">LHR</option>
</select>
<div id="area" style="display:none">
</div>
<script language="JavaScript">
var areas = {
'1' : { '1' : 'Kohnoor' },
'2' : { '1' : 'amanabad' }
}
$(function (){
var areaSelect = $('#area');
var citySelect = $('#city').change(function (){
var value = $(this).val();
if( value && typeof areas[value] != 'undefined' ){
areaSelect.empty().show();
for( var i in areas[value] ){
areaSelect.append('<input type="checkbox" name="area[]" value="'+i+'" />'+areas[value][i]+'<br />');
}
}else{
areaSelect.empty().hide();
}
});
});
</script>
I'm using Jquery and Ajax function to get data from MySql and put it in a div where can I select them.
It works like this:
When I select a country from the list Jquery runs a function to display a list of cities in selected country using getJson. That list is displayed in "inputString" div.
Now I want to show the same data in a html select form, not in a DIV as it is right now.
The HTML looks like:
<select name="country" id="country" class="country">
<option value="USA">USA</option>
<option value="UK">UK</option>
<option value="serbia">Serbia</option>
</select>
<input size="30" id="inputString" type="text" name="inputString" class="inp"/>
<div class="suggestionList" id="autoSuggestionsList"></div>
Jquery:
$(document).ready(function () {
$("#inputString").keyup(function () { // inputString is DIV where list of cities are listed
var up_country = $("#country option:selected").val();
$.getJSON("cities.php?queryString=" + up_country + "", function (data) {
if (data.length > 0) {
$.each(data, function (i, data) {
var city = data.city;
if (i < 19) {
$('#autoSuggestionsList').append('<li class="k' + i + '">' + city + '</li>');
}
});
}
});
});
});
How can I display the list of cities of the selected country in html select form like this one below if the select country was UK?
<select name="city" id="city" class="city">
<option value='London'>London</option>
<option value='Manchester'>Manchester</option>
<option value='Salford'>Salford</option>
</select>
$('#country').after('<select name="city" id="city" class="city"/>');
$.each(data, function(index, datum){
$('#city').append($('<option/>').val(datum).text(datum));
});
try something like that-
in your html:
<select name="city" id="city" ></select>
and your jQuery code:
$.each(data, function(i, data){
var city = data.city;
if(i < 19){
$('#city').append('<option>'+ city+ '</option>');
}
}
<select class="suggestionList" id="autoSuggestionsList"></select>
<script>
$.getJSON("cities.php?queryString=" + up_country +"", function(data) {
var content = '';
$.each(data, function(){
content += '<option value="' + this.city + '">' + this.city + '</option>';
});
$('#autoSuggestionsList').html(content);
});
</script>
The response from php can be a form or any other html content. You can load html from php if you don't necessarily need to populate the list with jquery
--for example--
response from php
echo '<form>
<select>
<option>London</option>
<option>Manchester</option>
<option>Salford</option>
</select>
</form>
';
ajax loaded content
$('#citiesList').html(data);