How to make 2 dependent option field? - javascript

I want my capital_city autocomplete field to show only options that are related to country_name. So when choose a country in the second option field show only cities that are realted to the selected country. Thank you.
Here is my view.php:
<div class="filtering">
<form class="searchbox_1">
Country Name: <input type="text" class="search_1" name="country_name" id="country_name" />
City Name: <input type="text" class="search_1" name="capital_city" id="capital_city" />
Date from <input class="search_1" type="date" name="from_date" id="from_date"/>
Date to <input class="search_1" type="date" value = "<?php echo date('Y-m-d')?>" name="to_date" id="to_date"/>
<center><button class="submit_1" type="submit" id="LoadRecordsButton">Search</button>
<input class ="submit_1" type="reset" value="Clear fields!"></center>
</form>
</div>
<div id="countryTable"></div>
<script type="text/javascript">
$(document).ready(function () {
//Prepare jTable
$('#countryTable').jtable({
title: 'Country\'s',
paging: true,
pageSize: 10,
sorting: true,
defaultSorting: 'country_name ASC',
selecting: true,
multiselect: true,
selectingCheckboxes: true,
selectOnRowClick: true,
actions: {
listAction: 'get_country',
createAction: 'create_country',
updateAction: 'update_country',
deleteAction: 'delete_country'
},
fields: {
country_id: {
key: true,
list: false
},
country_name: {
title: 'Country Name',
width: '11%'
},
country_code: {
title: 'Country Code',
width: '11%'
},
surface_area: {
title: 'Surface Area (m<sup>2</sup>)',
width: '13%'
},
continent_name: {
title: 'Continent Name'
},
continent: {
title: 'Continent Code',
width: '12%'
},
population: {
title: 'Population'
},
capital_city: {
title: 'Capital City'
},
record_date: {
title: 'Record Date',
type: 'date',
displayFormat: 'mm/dd/yy',
create: false,
edit: false,
sorting: false
}
},
$('#country_name').autocomplete({
source: 'list_country',
minLength: 0,
scroll: true,
autoFocus: true
}).focus(function() {
$(this).autocomplete("search", "")
.autocomplete( "widget" )
.addClass( "country_field" );
});
$('#capital_city').autocomplete({
source: 'list_city',
minLength: 0,
scroll: true,
autoFocus: true
}).focus(function() {
$(this).autocomplete("search", "")
.autocomplete( "widget" )
.addClass( "country_field" );
});
$('#LoadRecordsButton').click(function (e) {
e.preventDefault();
$('#countryTable').jtable('load', {
country_name: $('#country_name').val(),
capital_city: $('#capital_city').val(),
from_date: $('#from_date').val(),
to_date: $('#to_date').val()
});
});
$('#LoadRecordsButton').click();
});
</script>
</div>
Here is my model.php:
public function get_country_name() {
$searchTerm = filter_input(INPUT_GET, 'term');
$query = $this->db->query("SELECT DISTINCT country_name FROM country "
. "WHERE deleted=0 AND country_name LIKE '" . $searchTerm . "%' ORDER BY country_name ASC");
$row = array();
foreach ($query->result_array() as $ro) {
$row[] = $ro['country_name'];
}
echo json_encode($row);
}
public function get_city_name() {
$searchTerm = filter_input(INPUT_GET, 'term');
$query = $this->db->query("SELECT DISTINCT capital_city FROM country "
. "WHERE deleted=0 AND capital_city LIKE '" . $searchTerm . "%' ORDER BY capital_city ASC");
$row = array();
foreach ($query->result_array() as $ro) {
$row[] = $ro['capital_city'];
}
echo json_encode($row);
}
Here is my controller.php:
public function list_country(){
$this->load->model('Country_model');
$this->Country_model->get_country_name();
}
public function list_city(){
$this->load->model('Country_model');
$this->Country_model->get_city_name();
}
I have been looking for days to find a solution. Please help me. :-) .

Try adding something like this:
$('#country_name').change({
/*some code here*/
});
Then, transfer your $('#capital_city').autocomplete({}) inside, like this:
$('#country_name').change({
var country = $(this).val();
$('#capital_city').autocomplete({
source: 'list_city_' + country, /*see explanation below*/
minLength: 0,
scroll: true,
autoFocus: true
}).focus(function() {
$(this).autocomplete("search", "")
.autocomplete( "widget" )
.addClass( "country_field" );
});
});
Every time the country name is changed, the source of cities for auto-completion also changes accordingly.
For that to work, group your cities list by country when you fetch them through your model.
I was not able to test this code, and it may need some tweaks to work for you, but I hope it gives you some ideas to solve your problem. Good luck!

Related

jQuery Datables: Update Button class and text on the same row when it is selected

Sorry noob with Datatables but I need to ask this question. I created a laravel datatable using this api function:
$products = \DB::table('products')
->orderBy('id')
->select('product_id', 'product_title', 'product_image', 'meta_value', 'meta_id')
->get();
return DataTables::of($products)
->addColumn('checkbox', function($product) {
return '<div style="padding-left: 8px"><input id="checkbox-bulk" type="checkbox" name="ids[]" value="'. $product->product_id .'" /></div>';
})
->addColumn('action', function($product) {
$text = 'Hide';
$class='Polaris-Button';
if($product->meta_value && $product->meta_value == 1) {
$text = 'Show';
$class .= ' Polaris-Button--primary';
}
return '<button id="btn-edit-product" type="button" data-id="'. $product->product_id .'" class="'. $class .'"><span class="Polaris-Button__Content"><span class="Polaris-Button__Text">'. $text .'</span></span></button>';
})
->addColumn('image', function($product) {
return '<img src="' . $product->product_image . '" alt="noImage" width="55px" height="55px">';
})
->rawColumns([
'action',
'image',
'checkbox',
])
->make(true);
It has a checkbox which has the id that I need and other columns, here is my datatable:
let datatable = $('#products').DataTable({
serverSide: true,
processing: true,
responsive: true,
ajax: {
url: '{{ route('product.api') }}',
dataSrc: 'data'
},
columns: [
{ data: 'checkbox', name: 'checkbox', 'orderable': false, 'searchable': false },
{ data: 'product_id', name: 'product_id' },
{ data: 'product_title', name: 'product_title' },
{ data: 'image', name: 'image', orderable: false, searchable: false },
{ data: 'action', name: 'action', orderable: false, searchable: false },
]
});
I added a button outside the table to get the ids from the checkbox and process it by bulk, using these
$( datatable.$('input[type="checkbox"]:checked').each(function () {
ids.push($(this).val());
}));
However, after the bulk update I need to change the text and class of the action buttons which was selected and affected by the bulk update, and I tried this
$(datatable.$('input[type="checkbox"]:checked').each(function () {
let btn = $('#btn-edit-product');
btn.toggleClass("Polaris-Button--primary");
}));
However, it only gets the 1st row that was selected not the all the rows and I can't update the button class properly. How do I need to do this that if I select the button after bulk update I need to change all those buttons classes for each row. Thank you.
You have same ID in all places. Append a dynamic value in the id. Or else you can add onChange event in the checkbox. it will detect the exact element

How can I do multiple filtering with datatables?

I'm trying to filter my data by project status, client_id, and priority.
The project status and client works, when I add the priority the code. When I run the filters I do not get any errors and the page refreshes as though all is selected.
Here is my controller
$projects = Project::select('priority','project_name', 'client_id', 'completion_percent');
$projects->get();
return DataTables::of($projects)
->editColumn('priority', function ($row) {
if ($row->priority == "A"){
return '<label class="label label-success">' . strtoupper($row->priority) . '</label>';
}else if ($row->priority == "B"){
return '<label class="label label-danger">' . strtoupper($row->priority) . '</label>';
}
return '<label class="label label-warning">' . strtoupper($row->priority) . '</label>';
})
->rawColumns(['project_name', 'priority', 'action', 'completion_percent' ])
->make(true);
Here is my HTML for the filter of priority
<div class="col-md-3">
<div class="form-group">
<label class="control-label">#lang('app.menu.projects') #lang('app.priority')</label>
<select class="select2 form-control" data-placeholder="#lang('app.menu.projects') #lang('app.priority')" id="priority">
<option selected value="all">All</option>
<option value="A">A</option>
<option value="B">B</option>
</select>
</div>
</div>
And here is the java script
function showData() {
var status = $('#status').val();
var clientID = $('#client_id').val();
var priority = $('#priority').val();
var searchQuery = "?status="+status+"&client_id="+clientID+"&priority="+priority;
table = $('#project-table').dataTable({
responsive: true,
processing: true,
serverSide: true,
destroy: true,
ajax: '{!! route('admin.projects.data') !!}'+searchQuery,
"order": [[ 0, "desc" ]],
deferRender: true,
language: {
"url": "<?php echo __("app.datatable") ?>"
},
"fnDrawCallback": function( oSettings ) {
$("body").tooltip({
selector: '[data-toggle="tooltip"]'
});
},
columns: [
{ data: 'priority', name: 'priority'},
{ data: 'project_name', name: 'project_name'},
{ data: 'members', name: 'members' },
{ data: 'deadline', name: 'deadline' },
{ data: 'client_id', name: 'client_id' },
{ data: 'completion_percent', name: 'completion_percent' },
{ data: 'action', name: 'action' }
]
});
}
$('#status').on('change', function(event) {
event.preventDefault();
showData();
});
$('#client_id').on('change', function(event) {
event.preventDefault();
showData();
});
$('#priority').on('change', function(event) {
event.preventDefault();
showData();
});
I would do it like this using the Datatable search plug-in:
$.fn.dataTable.ext.search.push(function (settings, searchData, index, rowData, counter) {
let shouldDisplay = true;
let searchValue = $('#priority').val();
if (searchValue === 'A') {
shouldDisplay = (rowData. priority === 'A') ? true : false;
} else if (searchValue === 'B') {
shouldDisplay = (rowData. priority === 'B') ? true : false;
}
return shouldDisplay;
});
$('#priority').on('change', function() {
table.draw();
});
You can read more here on utilizing this plugin https://datatables.net/manual/plug-ins/search

Popover image on hover bootstrap table

I'm completely new to web technologies,
I have a table that retrieves data from a database and they are displayed with bootstrap table.
Check out the interface image
I have usernames;
each username has their own image.
I have the images for every username stored online.
with the following naming:
username= 111
has an image with the name 111.jpg
stored on localhost/images/111.jpg
What I want to achieve is when I hover over any username in the table, their image is displayed.
list-user.php file
<?php
require 'db.php';
$sqltran = mysqli_query($con, "SELECT * FROM users ")or die(mysqli_error($con));
$arrVal = array();
$i=1;
while ($rowList = mysqli_fetch_array($sqltran)) {
$name = array(
'num' => $i,
'user'=> $rowList['username'],
);
array_push($arrVal, $name);
$i++;
}
echo json_encode($arrVal);
mysqli_close($con);
?>
`
what matters from index.php file
<script type="text/javascript">
var $table = $('#table');
$table.bootstrapTable({
url: 'list-user.php',
search: true,
pagination: true,
buttonsClass: 'primary',
showFooter: true,
minimumCountColumns: 2,
columns: [{
field: 'num',
title: '#',
sortable: true,
},{
field: 'user',
title: 'Username',
sortable: true,
}, ],
});
</script>
Thats what I'm trying to accomplish something like this
What I want to accomplish (IMAGE )

How can i put hidden id with autocomplete jquery

I want to put hidden id when get the value from autocomplete for add to database but now when i get value from autocomplete and add to database it's add value is label name not the id of the data
<input type='text' id='id' name='id' class='id_line' placeholder='Item Code'/>
This my jquery code
$("#add_line").on('click',function(){
$('.tbl_add_line').append(data);
$('.id_line').autocomplete({
source: function (request, response){
$.ajax({
url : "<?php echo site_url('warehouse/get_id');?>",
dataType: "jsonp",
data : {
q: request.term
},
success: function( data ) {
response(data);
}
});
},
});
i++;
});
And this is function to get data to show in autocomplete
function get_id(){
$result = "";
if(isset($_GET['q'])){
$code = $_GET['q'];
$this->db->like("item_code",$code)->select('*');
$this->db->order_by("item_code");
$result = $this->db->from("tbl_item_code")->get()->result();
}
$arr = array();
foreach($result as $key){
$arr[] = array(
'id' => $key->id,
'value' => $key->id,
'label' => $key->item_code."(".$key->id.")",
);
}
echo $_GET['callback']."(".json_encode($arr).")";
}
You can use _renderItem method to add custom attributes to created elements.
Try this:
$(function() {
var projects = [{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
}, {
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
}, {
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}];
$("#project").autocomplete({
minLength: 0,
source: projects,
focus: function(event, ui) {
$("#project").val(ui.item.label);
return false;
},
select: function(event, ui) {
$("#project").val(ui.item.label);
$("#project-id").val(ui.item.value);
$("#project-description").html(ui.item.desc);
return false;
}
})
.autocomplete("instance")._renderItem = function(ul, item) {
return $("<li>")
.append("<a>" + item.label + "<br>" + item.desc + "</a>")
.appendTo(ul);
};
});
#project-label {
display: block;
font-weight: bold;
margin-bottom: 1em;
}
#project-icon {
float: left;
height: 32px;
width: 32px;
}
#project-description {
margin: 0;
p
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<div id="project-label">
Select a project (type "j" for a start):</div>
<input id="project">
<input type="text" id="project-id" disabled>
<p id="project-description"></p>
Fiddle here

Get json data from php using javascript

I am new to json .I am getting the data from php code in json format..
[
{
"Title": "New Event",
"TYPE": "info",
"StartsAt": "16 November 201512:00",
"EndsAt": "25 November 201512:00"
},
{
"Title": "Party",
"TYPE": "warning",
"StartsAt": "25 November 2015 09:30",
"EndsAt": "25 November 2015 5:30"
},
]
I have a javascript file demo.js
I want to receive this data in js file, currently the data is hardcoded. I want to show the events which I fetch from db.
vm.calendarView = 'month';
vm.calendarDay = new Date();
vm.events = [
{
title: 'An event',
type: 'warning',
//startsAt: moment().startOf('week').subtract(2, 'days').add(8, 'hours').toDate(),
//endsAt: moment().startOf('week').add(1, 'week').add(9, 'hours').toDate(),
startsAt:new Date(2015,10,1,1),
endsAt:new Date(2013,5,1,1),
draggable: true,
resizable: true
}, {
title: '<i class="glyphicon glyphicon-asterisk"></i> <span class="text-primary">Another event</span>, with a <i>html</i> title',
type: 'info',
startsAt: moment().subtract(1, 'day').toDate(),
endsAt: moment().add(5, 'days').toDate(),
draggable: true,
resizable: true
}, {
title: 'This is a really long event title that occurs on every year',
type: 'important',
startsAt: moment().startOf('day').add(7, 'hours').toDate(),
endsAt: moment().startOf('day').add(19, 'hours').toDate(),
recursOn: 'year',
draggable: true,
resizable: true
}
];
If the question is roughly "How do I get data from my database and output it as JSON in Javascript" then hopefully the following pseudo code will guide you in the right general direction.
<?php
include 'db.php';
$json=array();
/* Query the db */
$sql='select * from `events`;';
$res=$db->query( $sql );
if( $res ){
while( $rs=$res->fetch_object() ){
$json[]=array(
'title' => $rs->title,
'type' => $rs->type,
'startsAt' => $rs->startsAt,
'endsAt' => $rs->endsAt,
'draggable' => $rs->draggable,
'resizable' => $rs->resizable
);
}
}
$db->close();
$js_json_var=json_encode( $json, JSON_FORCE_OBJECT );
?>
<html>
<head>
<title></title>
<script>
var json=<?php echo $js_json_var;?>;
/* Other js code */
</script>
</head>
<body>
<h1>json</h1>
</body>
</html>
Javascript: AJAX request:
var events;
$.ajax({
url: '/data.php',
success: function(data){
events = JSON.parse(data);
}
});
data.php is like this
$db = new PDO(/* init connection here */);
print json_encode($db->query('select * from `tablename`')->fetchAll(PDO::FETCH_ASSOC));
// In javascript
$.ajax({
type: 'post',
url: 'data.php',
data: 'data',
cache: false,
success: function(data)
{
console.log(data);
}
});
// In data.php
header('Content-type: application/json');
$data = array();
$sql = "SELECT * FROM TABLE_NAME";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res))
{
$data[] = $row;
}
echo json_encode($data, true);

Categories