I create a search box with select2 multi-value select boxes. the data on select2 must list of Title Name that are based on the Project I selected before. But Select2 cannot load the data. Also, there is an error
"Uncaught Error: Option 'ajax' is not allowed for Select2 when attached to a element" how to solve it?
This is Controller Page
function get_title_by_keyword()
{
$keyword = $_POST['keyword'];
$cos_id = implode(',', $_POST['cos_id']);
if (isset($keyword)&&isset($cos_id))
{
die(json_encode($this->menu_model->get_title_by_keyword($keyword,$cos_id)));
}
}
This is Model Page
function get_title_by_keyword($keyword,$cos_id){
$query="SELECT t.id as id , t.name text
FROM db_mstr.m_title t
JOIN db_mstr.m_os os ON t.os_id = os.id
JOIN db_mstr.m_os osC ON os.cos_id = osC.id
JOIN db_mstr.m_bp_title bpt ON t.id = bpt.title_id AND bpt.is_deleted=0
JOIN db_mstr.m_bp bp ON bpt.bp_id = bp.id
where t.id like '%$keyword%' and osC.id in ($cos_id)
GROUP BY t.name";
return $this->db->query($query)->result();
}
This is View Page and JS
<label class="control-label col-sm-1">Project</label>
<div class="col-sm-4">
<select required multiple="multiple" id="title_cos" name="title_cos" class="" style="width:100%" data-placeholder="">
<?php
foreach ($comboCompany as $key)
{
?><option value="'<?=$key->value?>'" > <?=$key->text?> <?php
}
?>
</select>
</div>
<label class="control-label col-sm-1" style="padding-left: 4px;padding-right: 3px;">Title Name</label>
<div class="col-sm-4">
<select required multiple="multiple" class="" id=title_list name="title_list" style="width:100%">
<?php
foreach ($comboTitle as $key)
{
?><option value="<?=$key->id?>" > <?=$key->text?> <?php
}
?>
</select>
</div>
<script>
$(document).ready(function(){
$("#title_list").select2({
ajax: {
url: '<?=base_url();?>index.php/menu/get_title_by_keyword',
dataType: 'json',
type: "POST",
quietMillis: 1000,
data: function (term) {
return {
keyword: term,
cos_id: $('#title_cos').val()
};
},
results: function (data) {
return {
results: data
};
}
},
placeholder: 'Search for Title',
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 3,
});
});
</script>
Related
With this function I can correct delete single record:
` //delete order
public function delete_order($id)
{
$id = clean_number($id);
$order = $this->get_order($id);
if (!empty($order)) {
//delete order products
$order_products = $this->get_order_products($id);
if (!empty($order_products)) {
foreach ($order_products as $order_product) {
$this->db->where('id', $order_product->id);
$this->db->delete('order_products');
}
}
//delete invoice
$this->db->where('order_id', $order->id)->delete('invoices');
//delete order
$this->db->where('id', $id);
return $this->db->delete('orders');
}
return false;
}`
Now I try prepare function for delete multiple records.
In header table I add:
` <th scope="col" style="width: 25px;">
<div class="form-check">
<input class="form-check-input fs-15" type="checkbox" id="checkAll">
</div>
</th>`
and in foreach:
` <th scope="row">
<div class="form-check">
<input class="form-check-input fs-15" name="checkbox-table" type="checkbox" name="checkAll" value="<?php echo $item->id; ?>">
</div>
</th>`
Now I created action:
`<a class="dropdown-item" onclick="delete_selected_orders('<?php echo trans("confirm_products"); ?>');"><?php echo trans('delete'); ?></a>`
.js script
`<script>
//delete selected orders
function delete_selected_orders(message) {
swal({
text: message,
icon: "warning",
buttons: true,
buttons: [sweetalert_cancel, sweetalert_ok],
dangerMode: true,
}).then(function (willDelete) {
if (willDelete) {
var order_ids = [];
$("input[name='checkbox-table']:checked").each(function () {
order_ids.push(this.value);
});
var data = {
'order_ids': order_ids,
};
data[csfr_token_name] = $.cookie(csfr_cookie_name);
$.ajax({
type: "POST",
url: base_url + "order_admin_controller/delete_selected_orders",
data: data,
success: function (response) {
location.reload();
}
});
}
});
};
</script>`
order_admin_controller/delete_selected_orders
` /**
* Delete Selected Orders
*/
public function delete_selected_orders()
{
$order_ids = $this->input->post('order_ids', true);
$this->order_admin_model->delete_multi_orders($order_ids);
//reset cache
reset_cache_data_on_change();
}`
model
//delete multi order
public function delete_multi_orders($order_ids)
{
if (!empty($order_ids)) {
foreach ($order_ids as $id) {
$this->delete_order($id);
}
}
}`
When I check all and post delete multiple action then I see sweatalert to confirm delete, when I confirm I not see any error in console browser. But When I select multiple records and post then page refresh and orders not deleted.
I think function controller/model is correct. But im not sure with this in .js order_ids and in view table if I post order_ids correct.
I use Select 2 in my form where the option data in it I take from the database and I also add an "add new" button when the searched keyword is not in the database. what I want to ask is, what kind of way can I do to be able to create an action from the button. for example when the button is clicked I can display a text field.
For illustration, here is my code:
$('#add_penilai').select2({
placeholder: 'Change Name',
tags : true,
createTag: function (params) {
return {
id: params.term,
text: params.term,
newOption: true
}
},
templateResult: function (data) {
var $result = $("<span></span>");
$result.text(data.text);
if (data.newOption) {
$result.append(`<button type="button"
class="btn btn-secondary btn-sm ml-10"
onClick='Show()'> + Add New Item</button>`);
}
return $result;
},
escapeMarkup: function (markup) {
return markup;
}
});
.form-control.form-control-hide {
display: none;
}
<select class="form-control select2" id="add_penilai" name="nama_penilai" onchange="isi_otomatis()" data-width="100%">
<option value="Jhony">Jhony</option>
<option value="Kyra">Kyra</option>
<option value="Ronald">Ronald</option>
</select>
<input class="form-control form-control-hide" type="text" id="divisi" name="nama_instansi" />
I am dynamically loading a Select2 input with Ajax. Everything works fine, however, when I try to select a different value, It won't change for some reason. Here's an example of my problem: https://gyazo.com/f9ad7c3ead5fcd1d62740cc44f8d9691
As you can see, the value doesn't change when I click on it. Why does this happen? Maybe it helps when I say that both the first value and the other value have an ID of 1 (its data from different tables in the database) but different texts... How can I make it work?
$('.partnersupplierselect').select2({
ajax: {
dataType: "json",
type: "POST",
data: function (params) {
var group = $(this).parent().parent();
var choice = group.find('.partnersupplier:radio:checked').val();
return {
term: params.term,
'_token': token,
'choice': choice
};
},
url: '{{asset('logs/create/bmi/getpartnerssuppliers')}}',
cache: true,
processResults: function (data) {
return {
results: data
};
}
},
"language": {
"noResults": function () {
return "Geen partners / leveranciers gevonden.";
}
},
escapeMarkup: function (markup) {
return markup;
}
});
$('.partnersupplier').on('change', function(){
var group = $(this).parent().parent();
group.find('.partnersupplierselect').select2('val', '');
group.find('.partnersupplierselect').select2('data', null);
});
Here's the HTML, but that shouldn't be the problem. But in case someone wants to see it:
<div class="group">
<label class="mdl-radio mdl-js-radio mdl-js-ripple-effect" for="partner">
{{Form::radio('partnersupplier', 'partner', true, array('class' => 'mdl-radio__button partnersupplier', 'id' => 'partner'))}}
<span class="mdl-radio__label">Test1 </span>
</label>
<label class="mdl-radio mdl-js-radio mdl-js-ripple-effect margin-radio" for="supplier">
{{Form::radio('partnersupplier', 'supplier', false, array('class' => 'mdl-radio__button partnersupplier', 'id' => 'supplier'))}}
<span class="mdl-radio__label">Test2 </span>
</label>
<div class="form-group selectdiv" >
<label for="yearlypartnersuppliermaintainance">Blablabla<br></label>
<select id="yearlypartnersuppliermaintainance" name="yearlypartnersuppliermaintainance" class="searchselect searchselectstyle partnersupplierselect">
</select>
</div>
</div>
I figured it out!
I changed:
$('.partnersupplier').on('change', function(){
var group = $(this).parent().parent();
group.find('.partnersupplierselect').select2('val', '');
group.find('.partnersupplierselect').select2('data', null);
});
to:
$('.partnersupplier').on('change', function(){
var group = $(this).parent().parent();
group.find('.partnersupplierselect').empty().trigger('change');
});
For some reason, this works and the first thing doesn't. Weird, but at least I got it working!
views.php
<div class="input-group">
<input class="form-control" id="nomor_cari" maxlength="16" placeholder="No. CM / No. KTP">
script autocomplete
$('#nomor_cari').autocomplete({
source: get_no,
dataType: 'JSON'
});
function get_no
<?php
function get_no($q)
{
$this->db->select('NO_MEDREC');
$this->db->like('NO_MEDREC', $q);
$query = $this->db->get('PASIEN_IRJ');
if($query->num_rows > 0)
{
foreach ($query->result_array() as $row)
{
$row_set[] = htmlentities(ucfirst($row['NO_MEDREC']));
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($row_set));
}
echo $query->row();
}?>
but autocomplete didn't show anything.
if i use local variable , autocomplete works like it should be.
<script> var availableNumber = [
"0000000002",
"0000000020",
"0000000200",
"0000002000"
];
/<script>
and changes autocomplete to
$('#nomor_cari').autocomplete({
source: availableNumber,
dataType: 'JSON'
});
what did i missed? (im sure .js are loaded because when using local var , it works like charm)
just in case needed , here's my autoload
$autoload['libraries'] = array('database', 'email', 'session');
$autoload['helper'] = array('url', 'template', 'message', 'misc');
I think issue is in "source". Please try to use json like this
$('#nomor_cari').autocomplete({
source: function (request, response) {
$.getJSON("ful_url/get_no?term=" + request.term, function (data) {
response($.map(data.dealers, function (value, key) {
return {
label: value,
value: key
};
}));
});
},
});
i have a form with two select box. one is for the city and the other one for the area.
My requirement. When some one selects a city,The areas in the city must be captured from database and displayed in another select box.
i tried but, i have problem with my ajax. here is my code below.
view
<div class="location-group">
<label class="-label" for="city">
Location
</label>
<div class="">
<select id="city_select">
<option value="0"> select</option>
<?php foreach ($city as $cty) : ?>
<option value="<?php echo $cty->city_id; ?>"><?php echo $cty->name; ?></option>
<?php endforeach ?>
</select>
</div>
</div>
<div class="location control-group" id="area_section">
<label class="control-label" for="area">
Area
</label>
<div class="controls">
<select id="area_select">
<option value=""> Any</option>
<?php foreach ($area as $ara) : ?>
<option value="<?php echo $ara->ara_id; ?>"><?php echo $ara->name; ?></option>
<?php endforeach ?>
</select>
</div><!-- /.controls -->
</div><!-- /.control-group -->
controller
function __construct() {
parent::__construct();
//session, url, satabase is set in auto load in the config
$this->load->model('Home_model', 'home');
$this->load->library('pagination');
}
function index(){
$data['city'] = $this->home->get_city_list();
$data['type'] = $this->home->get_property_type_list();
$this->load->view('home', $data);
}
function get_area(){
$area_id = $this->uri->segment(3);
$areas = $this->home->get_area_list($area_id);
echo json_encode($areas);
}
Model
function get_area_list($id){
$array = array('city_id' => $id, 'status' => 1);
$this->db->select('area_id, city_id, name');
$this->db->where($array);
$this->db->order_by("name", "asc");
$this->db->from('area');
$query = $this->db->get();
$result = $query->result();
return $result;
}
Ajax
<script type="text/javascript">
$('#area_section').hide();
$('#city_select').on('change', function() {
// alert( this.value ); // or $(this).val()
if (this.value == 0) {
$('#area_section').hide(600);
}else{
//$("#area_select").html(data);
$.ajax({
type:"POST",
dataType: 'json',
url:"<?php echo base_url('index.php?/home/get_area/') ?>",
data: {area:data},
success: function(data) {
$('select#area_select').html('');
$.each(data, function(item) {
$("<option />").val(item.area_id)
.text(item.name)
.appendTo($('select#area_select'));
});
}
});
$('#area_section').show(600);
};
});
</script>
once i select a city, it must get all the areas in the city from database and display it in the area_select select box.
can any one please help me. Thanks.
Try to change this way.
Your ajax code
//keep rest of the code
$.ajax({
type:"POST",
dataType: 'json',
url:"<?php echo base_url('index.php?/home/get_area/') ?>",
data: {area:$(this).val()},//send the selected area value
Also show the area_section inside ajax success function
Your controller function
function get_area()
{
$area_id = $this->input->post('area');
$areas = $this->home->get_area_list($area_id);
echo json_encode($areas);
}
Hope it will solve your problem
Update
Try using your ajax update function like this
success: function(data) {
$('select#area_select').html('');
for(var i=0;i<data.length;i++)
{
$("<option />").val(data[i].area_id)
.text(data[i].name)
.appendTo($('select#area_select'));
}
}
Simple way to do that follow the instruction on this page
https://itsolutionstuff.com/post/codeigniter-dynamic-dependent-dropdown-using-jquery-ajax-exampleexample.html
demo_state table:
CREATE TABLE `demo_state` (
`id` int(11) NOT NULL,
`name` varchar(155) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
demo_cities table:
CREATE TABLE `demo_cities` (
`id` int(11) NOT NULL,
`state_id` int(12) NOT NULL,
`name` varchar(155) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
After create database and table successfully, we have to configuration of database in our Codeigniter 3 application, so open database.php file and add your database name, username and password.
application/config/database.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => 'root',
'database' => 'test',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
Read Also: How to make simple dependent dropdown using jquery ajax in Laravel 5?
Step 3: Add Route
In this step you have to add two new routes in our route file. We will manage layout and another route for ajax, so let's put route as bellow code:
application/config/routes.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['myform'] = 'HomeController';
$route['myform/ajax/(:any)'] = 'HomeController/myformAjax/$1';
Step 4: Create Controller
Ok, now first we have to create one new controller HomeController with index method. so create HomeController.php file in this path application/controllers/HomeController.php and put bellow code in this file:
application/controllers/HomeController.php
<?php
class HomeController extends CI_Controller {
/**
* Manage __construct
*
* #return Response
*/
public function __construct() {
parent::__construct();
$this->load->database();
}
/**
* Manage index
*
* #return Response
*/
public function index() {
$states = $this->db->get("demo_state")->result();
$this->load->view('myform', array('states' => $states ));
}
/**
* Manage uploadImage
*
* #return Response
*/
public function myformAjax($id) {
$result = $this->db->where("state_id",$id)->get("demo_cities")->result();
echo json_encode($result);
}
}
?>
Step 5: Create View Files
In this step, we will create myform.php view and here we will create form with two dropdown select box. We also write ajax code here:
application/views/myform.php
<!DOCTYPE html>
<html>
<head>
<title>Codeigniter Dependent Dropdown Example with demo</title>
<script src="http://demo.itsolutionstuff.com/plugin/jquery.js"></script>
<link rel="stylesheet" href="http://demo.itsolutionstuff.com/plugin/bootstrap-3.min.css">
</head>
<body>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Select State and get bellow Related City</div>
<div class="panel-body">
<div class="form-group">
<label for="title">Select State:</label>
<select name="state" class="form-control" style="width:350px">
<option value="">--- Select State ---</option>
<?php
foreach ($states as $key => $value) {
echo "<option value='".$value->id."'>".$value->name."</option>";
}
?>
</select>
</div>
<div class="form-group">
<label for="title">Select City:</label>
<select name="city" class="form-control" style="width:350px">
</select>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('select[name="state"]').on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url:"<?php echo base_url('index.php/Diplome/myformAjax/') ?>"+ stateID,
//url: '/myform/ajax/'+stateID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="city"]').empty();
$.each(data, function(key, value) {
$('select[name="city"]').append('<option value="'+ value.id +'">'+ value.name +'</option>');
});
}
});
}else{
$('select[name="city"]').empty();
}
});
});
</script>
</body>
</html>