How to fix bootstrap multiselect search data using ajax - php

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');

Related

I can't insert data of select from modal?

I tried to do the same for the input but With no chance however I did not understand if I has to be done with the change function should it be inserted seperately from the rest of the rest of the modal data
<select class="form-select form-select-lg mb-3" aria-label=".form-select-lg example" name="TypeCo" id="TypeCo">
<option selected name="TypeCo" id="TypeCo">Type de concentrateur</option>
<option value="Concentrateur Fixe">Concentrateur Fixe</option>
<option value="Concentrateur transportable">Concentrateur transportable</option>
</select>
<select class="form-select form-select-lg mb-3" aria-label=".form-select-lg example" name="CapCo">
<option selected name="CapCo" id="CapCo">Capacité de concentrateur</option>
<option value="5L">5L</option>
<option value="7L">7L</option>
<option value="10L">10L</option>
<option value="15L">15L</option>
</select>
and here is my script
$(document).ready(function() {
$(document).on('click', '#save', function() {
var fname = $('#fname').val();
var lname = $('#lname').val();
var tel = $('#tel').val();
var email = $('#email').val();
var TypeCo = $('#TypeCo').val();
var CapC = $('#CapCo').val();
alert(fname + lname + tel + email + TypeCo);
$.ajax({
url: "insert.php",
type: "post",
data: {
fname: fname,
lname: lname,
email: email,
tel: tel,
TypeCo: TypeCo,
CapCo = CapCo
},
success: function(data) {
$("#save").modal('hide');
alert('jj');
location.reload();
}
});
});
});
any help please ? it's my first project with ajax and I cannot really find a vid that can help me
This is indeed how you get the value from a form element in jQuery:
var TypeCo = $('#TypeCo').val();
However, you are targeting the wrong element. #TypeCo is currently targeting an <option> element:
<option selected name="TypeCo" id="TypeCo">Type de concentrateur</option>
You want to get the value of the <select> element itself (which contains <option> elements for the user to select that value). Move the name and id there:
<select class="form-select form-select-lg mb-3" aria-label=".form-select-lg example" name="TypeCo" id="TypeCo">
<option selected>Type de concentrateur</option>
<option value="Concentrateur Fixe">Concentrateur Fixe</option>
<option value="Concentrateur transportable">Concentrateur transportable</option>
</select>
Then you can use .val() exactly like you already do:
$('#TypeCo').on('change', function () {
let value = $('#TypeCo').val();
console.log(value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-select form-select-lg mb-3" aria-label=".form-select-lg example" name="TypeCo" id="TypeCo">
<option selected>Type de concentrateur</option>
<option value="Concentrateur Fixe">Concentrateur Fixe</option>
<option value="Concentrateur transportable">Concentrateur transportable</option>
</select>

PHP: Passing selected list value to another variable in the same page

I have a form, having two list boxes and based on the selected field from the first list, I have to fetch data from the database to create second list box.
I am trying to acheive this with post method, but unable to understand why mey second list is not populating with data...
PHP to fetch data for second list box
if (isset($_POST['val']))
{
$value = $_POST['val'];
$smt3 = $db->prepare('select floor from test where name_id =?');
$smt3->execute(array($value));
$HF_id = $smt3->fetchAll();
}
HTML to for the list boxes
<select class="Name" name="Profile_Name1" id="PC1">
<option value="A">AA</option>
<option value="B">BB</option>
<option value="c">CC</option>
<option value="d">DD</option>
</select>
<label>Home Floor </label>
<select name="Home_Floor" id="hfid"> <br />
<option value="">Home_Floor</option>
<?php foreach ($HF_id as $row){echo '<option value="' . $row['floor'] . '">' . $row ['floor'] . '</option>';}?>
</select>
Jquery
$('#PC1').on('click', function() {
$.post('user_info1.php', 'val=' + $(this).val(), function (response) {
$.ajax({
url: 'user_info1.php', //This is the current doc
type: "POST",
data: ({val: + $(this).val()}),
success: function(data){
}
});
You seem to expect the post function to trigger a loading of the page specified by the URL parameter.
Try something along the lines of this:
HTML
<select class="Name" name="Profile_Name1" id="PC1">
<option value="A">AA</option>
<option value="B">BB</option>
<option value="C">CC</option>
<option value="D">DD</option>
</select>
<label>Home Floor </label>
<select name="Home_Floor" id="hfid">
</select>
loaddata.php
if (isset($_POST['val']))
{
$value = $_POST['val'];
$smt3 = $db->prepare('select floor from test where name_id =?');
$smt3->execute(array($value));
$HF_id = $smt3->fetchAll();
$HF_array=array();
foreach ($HF_id as $row)
{
$HF_array[]=$row['floor'];
}
}
echo json_encode($HF_array);
javascript/jquery
jQuery('#PC1').on('click', function() {
jQuery.ajax({
url: 'loaddata.php',
type: "POST",
data: ({val: + $(this).val()}),
success: function(data){
//data should come as JSON string in the form of ['item1','item2','item3'] use JSON.parse to convert to object:
jQuery.each(JSON.parse(data), function(key, datavalue) {
jQuery('#hfid').append(
jQuery('<option>', { value : datavalue })
.text(datavalue)
);//end of append
});//end of each
}//end of success function
});//end of ajax datastruct and ajax call
});//end of on-click-function

build conditional select with codeigniter form helpers

I am trying to create two dropdown lists with the condition, that the second one should show the list based on the value, selected in the first one.
1st is city.
2nd is district within the city.
Both lists are populated from the database.
Here is an example
<td>City:</td>
<td>
<?=form_dropdown('contact_city', $sel_city, set_value('contact_city'), "class='select2'"); ?>
</td>
<td>District:</td>
<td >
<?=form_dropdown('contact_district', $sel_contact_district, set_value('contact_district'),"class='select2'"); ?>
</td>
$sel_contact_district should be reloaded and list selection updated after city value is changed.
Which approach should I use?
Using ajax you could populate the second dropdown based on the value of the first. Would look something like that:
$("#cityDropdown").on('change', function(){
$.post('api/listdistrictsfromcity',
{ city_id : $(this).val() },
function(response){
var $district_dropdown = $("#districtsDropdown").empty();
$.each(response, function(i, item){
$district_dropdown.append("<option value='" + item.value + "'>"+ item.text +"</option>");
});
});
});
Select2 supports methods that allow programmatic control of the component.
// var $example = $(".js-example-programmatic").select2();
$('body').on('click', '.select2', function(e) {
//var select_name = $(this).attr("your_select2_name");
$(this).val("your_option").trigger("change");
});
You can also add options like this:
$('.select2').select2('data', {id: 100, a_key: 'Lorem Ipsum'});
3rd Edit:
As you mention in your question that you need to select the option on the select dropdown to depend on the first dropdown selected option.
Here is the Two select box which changes the option depending on the first select box.
$("#select1").change(function() {
if ($(this).data('options') === undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<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>
<select name="select2" id="select2">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>

default select on ajax conditional dropdown select

Need help for setting up a default select option form my conditional dropdown select.
Here is my first dropdown select
<select name="category" id="category">
<option value="" disabled selected>Select category</option>
#foreach($categories as $cats)
<option value="{{$cats->id}}">{{$cats->name}}</option>
#endforeach
</select>
My dependent dropdown is like this
<select name="product" id="product">
<option value=""></option>
</select>
JS
<script>
$('#category').on('change',function(e){
console.log(e);
var cat_id = e.target.value;
$.get('/products?cat_id=' + cat_id, function(data){
$('#product').empty();
$.each(data, function(index, subcatObj){
$('#product').append('<option value="'+subcatObj.id+'">'+subcatObj.name+'</option>');
});
});
});
</script>
For a simple dropdown select, like the categories one, simply used the and it worked fine, but how can I have this default select for the products drowdown select?
Appreciate any help.
You can append something like this
$('#product').empty();
$('#product').append('<option value="" disabled selected>Select Product</option>');
});
$.each(data, function(index, subcatObj){
$('#product').append('<option value="'+subcatObj.id+'">'+subcatObj.name+'</option>');
});
i have seen you have used $('#product').empty(); and hence your included <option value=""></option> is getting removed altogether which you put in your html.
You can use .html() instead of .append() so you do not need to $('#product').empty(); as .html() will overwrite your dom.
And then you can only need to put this in your html
<select name="product" id="product">
</select>
And your javascript will be something like this
<script>
$('#category').on('change',function(e){
console.log(e);
var cat_id = e.target.value;
var response = '';
$.get('/products?cat_id=' + cat_id, function(data){
response = '<option value="" disabled selected>Select Product</option>';
$.each(data, function(index, subcatObj){
response .= '<option value="'+subcatObj.id+'">'+subcatObj.name+'</option>';
});
$('#product').html(response);
});
});
</script>
you can find difference between .html() and .append() here What is the difference between .empty().append() and .html()?

Ajax call for dynamic menu works for first <select> element, but not additional ones

i'm trying to create a dynamic menu with jquery, and I want to populate the subsequent menu with Ajax data (taken from a DB).
I then want to be able to add additional dropdowns and retain the same functionality. I have it working for a single drop down and the ajax call is working, but it wont work for additional dropdowns that are addded via jquery (Repeat) function.
I dont think that I need to add a counter variable to the php as I'm handling the incrementation in the jquery, but I just cant get the input from the additional dropdowns (the ones that go into (.additionalsubj') into the Ajax - i cant even get them to show in Firebug.
I'm a bit stuck - any thoughts would be massively appreciated.
HTML:
<h3>Primary Subject</h3>
<div class="subjselect">
<div class="select">
<select id="subject">
<option value="">Subject</option>
<option value="math">Math</option>
<option value="science">Science</option>
<option value="languages">Languages</option>
<option value="humanities">Humanities</option>
<option value="econ">Economics/Finance</option>
<option value="gmat">GMAT</option>
<option value="sat">SAT</option>
</select>
<select id="topic">
<option value="">Topic</option>
<option value="math">Math</option>
<option value="science">Science</option>
<option value="languages">Languages</option>
<option value="humanities">Humanities</option>
<option value="econ">Economics/Finance</option>
<option value="gmat">GMAT</option>
<option value="sat">SAT</option>
</select>
</div>
</br>Add Another Subject
</div>
Jquery:
var counter=1;
$(document).on('change', 'select#subject'+counter+'', function(){
var subject = $("select#subject"+counter+">option:selected").text();
var selector=$("select#subject"+counter+"");
console.log(selector);
console.log(subject);
$.ajax({
type: 'GET',
url: 'tutorprofileinput.php',
data: {"subject": subject},
dataType:'json',
success:function(data){
console.log(data);
var options = [];
$.each(data, function (key, val) {
options += '<option value="' + val.topic + '">' + val.topic + '</option>';
console.log(options);
});
$("select#topic").html(options);
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
});
function Repeat(obj){
counter++;
console.log(counter);
var selecoptions = '<div class="select"><select id="subject'+counter+'"><option value="">Subject</option><option value="math">Math</option><option value="science">Science</option><option value="languages">Languages</option><option value="humanities">Humanities</option><option value="econ">Economics/Finance</option><option value="gmat">GMAT</option><option value="sat">SAT</option></select></div><div class="select"><select id="topic'+counter+'"><option value="">Topic</option></select></div>';
$('.additionalsubj').append(selecoptions);
console.log($('.additionalsubj'));
}
and the PHP getting the data from the database:
<?php
include("php_includes/db_conx.php");
if (isset($_GET['subject'])){
$subject = $_GET['subject'];
$query = ("SELECT subject.id, topic FROM topics, subject WHERE subject='$subject' AND subject.id=topics.subjID ORDER BY subject");
$result = mysqli_query($db_conx, $query);
$rows = array();
while($r = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$rows[] = $r;
}
echo json_encode($rows);
exit();
}
?>
Use
$(document).on('change','select[id^=subject]',function(){
because you are adding counter which is set to one by default so i don't think its even work for first select box.
So use above code that will work for all selects whose id starts with subject.

Categories