build conditional select with codeigniter form helpers - php

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>

Related

Set Option Value as Select text

Need assistance
I need to have a select function where as
<select class="form-control">
<option value="4100">4100 : Mass Collections</option>
<option value="4200">4200 : Stole Fees</option>
<select>
now I don't want to include the code description after selecting an option, it should be code only appearing on the select box like this.
I have tried this Jquery script
$('select').change(function() {
var code= $('option:selected',this).text().split(' : ');
$('option:contains('+code[0]+')',this).val(code[0]);
})
but every time I do this checking in dropdown the option omitted the description entirely. How do I prevent this.
thanks in advance
You can follow the idea of this answer: add the description only when the element have focus:
$('select').on("focus", function(s) {
for (var o of this.options) {
o.textContent = o.getAttribute('value') + ': ' + o.dataset.descr;
}
});
$('select').on("blur", function(s) {
for (var o of this.options) {
o.textContent = o.getAttribute('value');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control">
<option value="4100" data-descr="Mass Collections">4100</option>
<option value="4200" data-descr="Stole Fees">4200</option>
<select>
This is the best that I could do.
$(document).ready(function (){
$('select').change(function(s) {
for (var option of this.options) {
option.label = option.text;
};
this.selectedOptions[0].label = this.selectedOptions[0].value;
});
});
Better to check it with more options,
<select class="form-control">
<option value="4100">4100 : Mass Collections</option>
<option value="4200">4200 : Stole Fees</option>
<option value="4300">4300 : Something Else</option>
<select>

How to fix bootstrap multiselect search data using ajax

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

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 get select tag id for passing through ajax

select id section
script section in head
So this is the situation.
I have this
<select name="users" onchange="showUser(this.value)" id="1">
<option value="">Select a person:</option>
<option value="'.$lectures[4][0].'">'.$lectures[4][0].'</option>
<option value="'.$lectures[5][0].'">'.$lectures[5][0].'</option>
<option value="'.$lectures[6][0].'">'.$lectures[6][0].'</option>
<option value="'.$lectures[7][0].'">'.$lectures[7][0].'</option>
</select>
Like this I have lots of select element in the page. I want to pass two value through ajax.
One is selected option value. Which I have done successfully.
Other is the I want to pass select tag id. In this case it is 1.
So Could you help me in the ajax part
xmlhttp.open("GET","optiondetails.php?q="+str,true);
xmlhttp.send();
How to pass this value through ajax. Please keep in mind that I have to do this for many select tag. So I cannot pass them directly by value.
Thanks for you help.
try this:
$(document).ready(function(){
$('select').change(function(){
var opt = $(this).find('option:selected');
console.log(opt.val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="1">
<option value="dog">dog</option>
<option value="cat">cat</option>
</select>
<select id="2">
<option value="chocolate">chocolate</option>
<option value="pizza">pizza</option>
</select>
I used jQuery selector to get the selected option inside the changed select element
I think this is more convenient way to do that:
$(document).ready(function(){
$(document).on('change', 'select', function(){
var optVal = $(this).val();
var id = $(this).attr('id');
$.ajax({
method: "GET",
url: "optiondetails.php",
data: {q:optval, tag_id:id},
cache: false
}).done(function(response){
console.log(response);
});
});
});

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