Need to append to select using JQuery - javascript

I need to append a HTML select option using jQuery. I have a piece of code that when a drop down is clicked, it fetches sub functions via AJAX. Once this is done, I also need to to add another option tag with a value of 99 and text of Other sub function. My code:
$.ajax({
type: "POST",
data: {function_id: function_id},
url: '<?php echo WEB_URL; ?>includes/ajax/target_audience_sub_functions.php',
dataType: 'json',
success: function(json) {
var $el = $("#target_audience_sub_function");
$el.empty(); // remove old options
$el.append($("<option></option>").attr("value", '').text('Please Select'));
$.each(json, function(value, key) {
$el.append($("<option></option>").attr("value", value).text(key));
});
$el.append($("<option></option>").attr("value", '99').text('Other sub function'));
}
});
The $el.append is the code I am trying to use to add the other option tag, but it doesn't work. I only get the ones from the AJAX. incidentally, the first append doesn't work either.
HTML
<div class="form-group">
<label for="target_audience_sub_function">Sub-Function</label>
<select data-selectedSubFunction="<?php echo (isset($audience)) ? $audience['target_audience_sub_function'] : ''; ?>" class="form-control light_grey_bg ta_sub_function" id="target_audience_sub_function" name="target_audience_sub_function[]">
<option value="">-- Choose sub function --</option>
<?php $get_functions = $db->get_all('sub_functions');
foreach ($get_functions as $function) { ?>
<option value="<?php echo $function['sub_function_id']; ?>" <?php echo isset($audience) ? $audience['target_audience_sub_function'] == $function['sub_function_id'] ? "selected='selected'" : "" : ''; ?> ><?php echo $function['sub_function_name']; ?></option>
<?php } ?>
</select>
</div>

Your code should work, I just tried it and the select got populated as you want it.
var json = {
0: 'Hello',
1: 'Bobby'
};
$(function() {
var $el = $("#target_audience_sub_function");
$el.click(function() {
$el.empty(); // remove old options
$el.append($("<option></option>").attr("value", '').text('Please Select'));
$.each(json, function(value, key) {
$el.append($("<option></option>").attr("value", value).text(key));
});
$el.append($("<option></option>").attr("value", '99').text('Other sub function'));
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="target_audience_sub_function"></select>
Maybe the success callback is never executed and the options you see are the one printed by PHP ?

Related

Dynamically load second bootstrap selectpicker based on user input of first selectpicker in codeigniter

I want to load data from the database to the second selectpicker based on the input id of the first selectpicker. In the database id of the first selectpicker is the foreign key of the second selectpicker.
View file
1st selectpicker
<select name="depot_select" id="depot_select" class="selectpicker" data-live-search="true" value="<?php echo set_value('depot_select');?>">
<option value="">No Depot Selected</option>
<?php echo $depots['depot'] ?>
</select>
2nd selectpicker
<select class="selectpicker" data-live-search="true" name="route_select" id="route_select" value="<?php echo set_value('route_select');?>">
<option value="">No Route Selected</option>
<?php echo $routes['route']?>
</select>
Ajax
function fetchDepot(){
$.ajax({
type :'POST',
url : '<?php echo base_url('transporter_dashboard/bus/get_depots'); ?>',
dataType: 'json',
success : function(data)
{
$('#depot_select').empty();
var example = $('#depot_select').selectpicker('val', data['data']);
console.log("depot_select" + example);
if(!$.isEmptyObject(data))
{
$.each(data, function(i,o)
{
var depot = $('#depot_select').append('<option value="'+ o['dpt_id'] +'">'+o['dpt_name'] +' </option>');
});
}
$('#depot_select').selectpicker('refresh');
fetchRoute();
},
error: function()
{
alert('error occour..........!');
}
});
}
function fetchRoute()
{
$.ajax(
{
type :'POST',
url :'<?php echo base_url('transporter_dashboard/bus/get_routes'); ?>',
data : { dpt_id : $('#depot_select option:selected').val()},
dataType: 'json',
success : function(data)
{
$('#route_select').empty();
$('#route_select').selectpicker('val', data['data']);
if(!$.isEmptyObject(data))
{
$.each(data, function(i,o)
{
var route = $('#route_select').append('<option value="'+ o['rot_id'] +'">'+ o['rot_name'] +'</option>');
});
}
$('#route_select').selectpicker('refresh');
},
error: function(data){
alert('error occour..........!');
}
});
}
Controller
function get_depots()
{
echo json_encode($this->bus_model->get_depots());
}
function get_routes()
{
if ($this->input->post('dpt_id'))
{
echo json_encode($this->bus_model->get_routes($this->input->post('dpt_id')));
}
}
Model
function get_depots()
{
$this->db->select('*');
$data = $this->db->get('depots')->result_array();
return $data;
}
function get_routes($id)
{
$data = array();
$this->db->select('*');
$this->db->where('dpt_id',$id);
$data = $this->db->get('routes')->result_array();
return $data;
}
According to the above code, only the id of the first option goes to the backend every time despite what option is selected. Then database load only those data which belongs to the id of the first option.
Finally, I found the answer to this question. We need to call fetchRoute() function inside of the $( document ).ready()

how to retrieve ajax data in "multiple" drop box?

I have 2 multiple select drop box.. form one I want to inflate the other multiple select drop box.. can anyone help me with this?
When I get result from the jQuery or ajax i want that result to display in 2nd number multiple select drop box...
this is my ajax..
function demo1() {
var emp_id = document.getElementById("employeeName").value;
alert(emp_id);
var datastring = "emp_id=" + emp_id;
//alert (emp_id);
$.ajax({
type: "POST",
url: "search_emp.php",
data: datastring,
dataType: "text",
//async: false,
success: function (data) {
//$("#clname").append(data);
$('#clname').html(data);
//document.getElementById("clname").innerHTML=data;
}
});
}
This are 2 multiple drop box..
<label>Select Employee </label>
<select multiple="multiple" class="w300" name="employeeName[]" id="employeeName" >
<?php $result = $conn->query("SELECT id,first_name,last_name,employee_id FROM employees");
while ($row = $result->fetch_assoc()){ ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['id']; ?><?php echo $row['first_name']; ?>
<?php echo $row['last_name'] ?></option>
<?php } ?>
<!--<?php echo $option;?>-->
<!--<?php echo $option2;?>-->
</select>
</br>
<label>Select Client</label>
<select multiple="multiple" class="w300" name="clname[]" id="clname">
<!--<?php echo $c;?>-->
</select>
.html() will set the innerHTML content of a DOM element, you can't do that on a <select>. There are two ways to solve it:
1) Quick & dirty: replace HTML
Make your search_emp.php also return the HTML code for the <select>, like this:
echo '<select multiple="multiple" class="w300" name="clname[]" id="clname">';
while($row = mysqli_fetch_assoc($ress)) {
echo '<option value="'.$row['gn_id'].'">'.$row['gamename'].'</option>';
}
echo '</select>';
Then you can use jQuery.replaceWith() to replace the whole DOM element:
$('#clname').replaceWith(data);
2) Much nicer: Build DOM from JSON
Instead of returning HTML code, your search_emp.php should return JSON, something like
[
{
"gn_id": "123",
"gamename": "superduper client"
},
{
"gn_id": "234",
"gamename": "another client"
}
]
You can easily do this by passing the client array to PHP's json_encode() and add a JSON content type header (Note that you will have to change the dataType attribute of $.ajax to "json" or you could use the shortcut function $.json():
// identify the content as JSON
header('Content-Type: application/json');
// put your MySQL query here.
// if errors occur, send a HTTP 500 header and return a useful error message as JSON
// collect results in an array
$rows = array();
while($row = mysqli_fetch_assoc($ress)) {
$rows[] = $row;
}
// return the results as a JSON list
echo json_encode($rows);
Before you make the AJAX call, you would want to remove all existing options from the select. In the success function of the AJAX call, you can loop through the results and append them to the select:
// reset the select options
$('#clname').empty();
// make the ajax call
$.ajax({
type: "POST",
url: "search_emp.php",
data: datastring,
dataType: "json",
success: function (data) {
// build the options from the JSON data
for (let client of data) {
$('#clname').append('<option value="' + client.gn_id + '">' + client.gamename + '</option>');
}
},
// optional, but good to have: error handling
error: function (data) {
alert("An error occurred:\n" + data.error)
}
});
jsfiddle
Note: let client of data only works in modern browsers (ES2015 compatible). If you want to support older browsers, do an old-fashioned for (len=data.length, i=0; i<len; ++i) loop. Or use jQuery.each() (although this might be slower)

Populate dropdown list from another dropdown list

I'm trying to populate a select menu based on the value selected on another select menu.
So far, I managed to get the value and my PHP code does return the values as JSON. However, I can't seem to figure out how to show the data in the next select menu.
<div class="form-group">
<label for="laptopBrand">Laptop Brand</label>
<select class="form-control" id="laptopBrand">
<?php foreach($laptop_brands as $laptop_brand): ?>
<option value="<?= $laptop_brand['Lbrand'] ?>"><?= $laptop_brand['Lbrand'] ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="laptopSeries">Laptop Series</label>
<select class="form-control" id="laptopSeries">
</select>
</div>
JQuery
$("#laptopBrand").change(function(){
var lbrand = $(this).val();
$.ajax({
type: "POST",
data: 'laptopSeries='+lbrand,
url: 'includes/fetch.php',
dataType: 'json',
success: function(json) {
var a = JSON.parse(json);
alert(a);
var $el = $("#laptopSeries");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
$.each(json, function(value, key) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
}
});
});
PHP
if($_POST){
$laptopSeries = $_POST['laptopSeries'];
try{
$stmt = $db_con->prepare("SELECT `Lseries` FROM `laptop` WHERE `Lbrand` = '$laptopSeries'");
$stmt->execute();
$series = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($series as $series) {
$array = array($series['Lseries'] => $series['Lseries']);
echo json_encode($array);
}
}catch(PDOException $e){
echo $e->getMessage();
}
}
Do like this and make sure your server code return exactly what you want to fill in key and value.
$.each(a,function(key, value) // a or jsondata
{
$select.append('<option value=' + key + '>' + value + '</option>');
});

Append json data to HTML List box

HTML code is :
<select name="ser" id="ser" class="form-control" onchange="getPrice(this.value);">
<option value="">--Select--</option>
<option value="Value11">Value1</option>
<option value="Value2">Value2</option>
</select>
<select name="freeitem" id="freeitem" class="form-control">
</select>
Js Code :
function getPrice(val) {
$.ajax({
type: 'post',
url: 'get_sales_price.php',
data: {
get_option: val
},
dataType: 'json',
success: function(response) {
console.log(response)
$('#freeitem').html(response.fritm);
}
});
}
and Php Code is :
$option = $_POST['get_option'];
$data = array();
$prdqty = $db->execute("select product_name from master_purchase where product_code='$option' and delet='0'");
while ($tqty = $prdqty->fetch_assoc())
{
$data['fritm'] = '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';
}
echo json_encode($data);
while we selecting first selectbox content, need to add some data to second select box from database, we almost done the things but the second select box didn't show any values ,please help us to resolve the above problem
I tried your code with some hard code value and it perfectly working fine:-
Html+Jquery (in single page with .html extension):-
<select name="ser" id="ser" class="form-control" onchange="getPrice(this.value);">
<option value="">--Select--</option>
<option value="Value11">Value1</option>
<option value="Value2">Value2</option>
</select>
<select name="freeitem" id="freeitem" class="form-control">
</select>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script><!-- added jquery library-->
<script type="text/javascript">
function getPrice(val) {
$.ajax({
type: 'post',
url: 'get_sales_price.php',
data: {
get_option: val
},
dataType: 'json',
success: function(response) {
console.log(response)
$('#freeitem').html(response.fritm);
}
});
}
</script>
Php (with hard-coded value):-
<?php
$option = $_POST['get_option'];
$data = array();
$data['fritm'] = ''; // you need to define it as empty string first
for($i = 0;$i<10;$i++) // hard-code started
{
$data['fritm'] .= '<option value="'.$i.'">'.$i.'</option>'; // append each option to the string one-by-one and check `.=` also
}
echo json_encode($data);
Output:-
http://prntscr.com/auyn7i
http://prntscr.com/auymzf
http://prntscr.com/auynij
Note:- problem may be occuring because either you missed jquery library of concatenation inside loop or some other error in your php file.
You need to do two things:
1) concatenate results in while loop. You are re-assigning the array variable causing latest one to overwrite the old one.
This way, only old value will be appended.
Change
$data['fritm'] = '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';
To
$data['fritm'] .= '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';
2) Change
$('#freeitem').html(response.fritm);
To
$('#freeitem').append(response.fritm);
As you are just appending options to drop down, not changing its HTML.

Choosing a chained select option with jquery using Codeigniter

I'm not much good at jquery and ajax, and I'm now having difficulties on a select box. I use CI and My code is below.
Another select box "category" data will be show according to the "brand". How can I carry data from "brand" and show data in "category" with jquery?
View
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?>
</option>
<?php
}
}
?>
</select>
<select name="category" class="form-control" id="category" required>
</select>
Ajax
<script>
$(function() {
$("#brand").on('change', function() {
var brand = $(this).val();
$.ajax ({
type: "post",
url: "<?php echo base_url(); ?>receiving/showCategory",
dataType: 'json',
data: 'brand='+brand,
success: function(msg) {
var options;
for(var i = 0; i<msg.length; i++) {
options = '<option>'+msg.category[i].category_name+'</option'>;
}
$('#category').html(options);
}
});
});
});
</script>
Controller
function showCategory() {
$brand_id = $this->input->post('brand');
$data['category'] = $this->item_model->category($brand_id);
echo json_encode($data);
}
My category table contains: category_id, category_name, brand_id.
use ajax onchange. .in your view file..
<select name="brand" class="form-control" id="brand" required onchange="brand(this.value,'divid')">
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?>
</option>
<?php
}
}
?>
</select>
<div id="divid">
<select name="category" class="form-control" id="category" required>
<option>Select Category</option>
</select>
</div>
<script>
function brand(id,divid)
{
$.ajax({
type: "POST",
data: "pid="+id,
url: '<?php echo base_url(); ?>receiving/showCategory ?>',
success: function(html){
$('#'+divid).html(html);
}
});
}
</script>
in your function showCategory() :
<div id="divid">
<select name="category" class="form-control" id="category" required>
$brandid = $this->input->post('pid');
//you can pass this brand id to your query and echo the category in option value//
<option>//your result //</option>
</select>
</div>
You need to concat the all values in success function like
options += '<option>'+msg.category[i].category_name+'</option'>;
$('#category').html(options);
Look like your code is correct, but need to change a little bit in ajax request.
You need to parse the data return into parseJson first. The options variable in for loop should concatenate with += code. See example below:
<script>
$(function() {
$("#brand").on('change', function() {
var brand = $(this).val();
$.ajax ({
type: "post",
url: "<?php echo base_url(); ?>receiving/showCategory",
dataType: 'json',
data: 'brand='+brand,
success: function(msg) {
var data = $.parseJSON(msg),options;
for(var i = 0; i<data.length; i++) {
options += '<option>'+data.category[i].category_name+'</option'>;
}
$('#category').html(options);
}
});
});
});
</script>
In case you have a problem with this code, you should change variable in codeigniter part for the variable that hold the results. You can see my working code below as an example :
Js Code
$.ajax({
type : 'POST',
url : '<?php echo base_url();?>controller/function_name',
dateType : 'json',
data : {depart_id : _depart_id.val()},
success : function(data){
var json_data = $.parseJSON(data),
options;
for(var i = 0; i<json_data.length; i++){
options += '<option value="'+json_data[i].destination_id+'">'+json_data[i].location+'</option>';
}
_destination_id.html(options);
}
});
Here is codeigniter code(php)
$destination = $this->custom_model->get_destination_distinct($table,$where);
echo json_encode($destination);

Categories