I am going to develop three autocomplete dropdown boxes using jQuery ajax for country state and city on my laravel project. I can implement simple html dropdowns using ajax. But while using jQuery autocomplete it automatically adds an input field in which it puts the value over selecting options from dropdown.
The issue is I am getting only values as text string from input field where I need the id of country which is my database. Previously I was able to get this id using html select element by using the value attribute but it seems there no way to get this id from input field.
How to get this and moreover how to use auto complete for multiple select boxes which needs to be auto changed by selecting options from any select boxes?
html select elements
<div class="ui-widget">
<p style="float:right;display:block;font-size:15px;">
<select id="country" name="sel_countries" required=""><option value="">Select Country</option>
#foreach ($countries as $country)
<option value="{{ $country->id }}">
{{ $country->name }}
</option>
#endforeach
</select>
<select id="state" name="sel_states" required=""><option value="">Select State</option></select>
<select id="city" name="sel_cities" required=""><option value="">Select City</option></select>
</p></div>
html ajax request
$('#country').change(function(){
var cid = $(this).val();
if(cid){
$.ajax({
type:"get",
url:"<?php echo $url; ?>/getStates/"+cid,
success:function(res)
{
if(res)
{
$("#state").empty();
$("#city").empty();
$("#state").append('<option>Select State</option>');
$.each(res,function(key,value){
$("#state").append('<option value="'+key+'">'+value+'</option>');
});
}
}
});
}
});
$('#state').change(function(){
var sid = $(this).val();
if(sid){
$.ajax({
type:"get",
url:"<?php echo $url; ?>/getCities/"+sid,
success:function(res)
{
if(res)
{
$("#city").empty();
$("#city").append('<option>Select City</option>');
$.each(res,function(key,value){
$("#city").append('<option value="'+key+'">'+value+'</option>');
});
}
}
});
}
});
bootstrap autocomplete code
$( function() {
$.widget( "custom.combobox", {
_create: function() {
this.wrapper = $( "<span>" )
.addClass( "custom-combobox" )
.insertAfter( this.element );
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function() {
var selected = this.element.children( ":selected" ),
value = selected.val() ? selected.text() : "";
this.input = $( "<input>" )
.appendTo( this.wrapper )
.val( value )
.attr( "title", "" )
.addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy( this, "_source" )
})
.tooltip({
classes: {
"ui-tooltip": "ui-state-highlight"
}
});
this._on( this.input, {
autocompleteselect: function( event, ui ) {
ui.item.option.selected = true;
this._trigger( "select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function() {
var input = this.input,
wasOpen = false
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.attr( "height", "" )
.tooltip()
.appendTo( this.wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: "false"
})
.removeClass( "ui-corner-all" )
.addClass( "custom-combobox-toggle ui-corner-right" )
.on( "mousedown", function() {
wasOpen = input.autocomplete( "widget" ).is( ":visible" );
})
.on( "click", function() {
input.trigger( "focus" );
// Close if already visible
if ( wasOpen ) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
});
},
_source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( this.element.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text,
value: text,
option: this
};
}) );
},
_removeIfInvalid: function( event, ui ) {
// Selected an item, nothing to do
if ( ui.item ) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children( "option" ).each(function() {
if ( $( this ).text().toLowerCase() === valueLowerCase ) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if ( valid ) {
return;
}
// Remove invalid value
this.input
.val( "" )
.attr( "title", value + " didn't match any item" )
.tooltip( "open" );
this.element.val( "" );
this._delay(function() {
this.input.tooltip( "close" ).attr( "title", "" );
}, 2500 );
this.input.autocomplete( "instance" ).term = "";
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
$( "#country" ).combobox();
$( "#toggle" ).on( "click", function() {
$( "#country" ).toggle();
});
} );
.custom-combobox {
position: relative;
display: inline-block;
}
.custom-combobox-toggle {
position: absolute;
top: 0;
bottom: 0;
margin-left: -1px;
padding: 0;
}
.custom-combobox-input {
margin: 0;
padding-top: 2px;
padding-bottom: 5px;
padding-right: 5px;
}
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
<p style="float:right;display:block;font-size:15px;">
<select id="country" name="sel_countries" required=""><option value="">Select Country</option>
<option value="1">
INDIA
</option>
<option value="1">
USA
</option>
<option value="1">
UK
</option>
<option value="1">
AUSTRALIA
</option>
<option value="1">
BRAZIL
</option>
</select>
<select id="state" name="sel_states" required=""><option value="">Select State</option></select>
<select id="city" name="sel_cities" required=""><option value="">Select City</option></select>
</p></div></div>
Related
Good day! I am new in Vuejs. Please help me.
I want to disable the select option after I select and set the select to default value.
for example
<select name="recipient" #change="changeFunc($event)">
<option>--Select--</option>
<option v-for="recipient in recipients" :key="recipient.id" :value="recipient.id" :disabled="recipient.disabled">{{ recipient.name }}</option>
</select>
export default {
data: function() {
return {
recipients: [
{'id':3, 'name':'aaa'},
{'id':5, 'name':'bbb'},
{'id':8, 'name':'ccc'}
],
}
},
method: {
changeFunc(e) {
//TODO disable the select value and set to default value
}
}
}
Please help how to do it. Thank you.
Try the following code
<select name="recipient" v-model="selected" #change="changeFunc($event)">
<option>--Select--</option>
<option v-for="recipient in recipients" :key="recipient.id" :value="recipient.id" :disabled="recipient.disabled">{{ recipient.name }}</option>
</select>
export default {
data: function() {
return {
selected: {},
recipients: [
{'id':3, 'name':'aaa', 'disabled': false},
{'id':5, 'name':'bbb', 'disabled': false},
{'id':8, 'name':'ccc', 'disabled': false}
],
}
},
method: {
changeFunc(e) {
const index = this.recepients.findIndex((el) =>{
if(el.id == this.selected){
return true;
}
});
if(index){
this.recepeints[index].disabled = true;
this.selected = "";
}
}
}
}
The changeFunc() find index of selected value and set disabled to true and reset selected value
You can achieve this with a simple approach by iterating the input array on option change.
this.recipients.forEach(obj => {
obj['disabled'] = (obj.id === this.recipient)
});
Live Demo :
new Vue({
el: '#app',
data: {
recipient: '',
recipients: [
{'id':3, 'name':'aaa'},
{'id':5, 'name':'bbb'},
{'id':8, 'name':'ccc'}
]
},
methods: {
changeFunc() {
this.recipients.forEach(obj => {
obj['disabled'] = (obj.id === this.recipient)
});
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<select v-model="recipient" #change="changeFunc">
<option value="">--Select--</option>
<option v-for="recipient in recipients" :key="recipient.id" :value="recipient.id" :disabled="recipient.disabled">{{ recipient.name }}</option>
</select>
</div>
I want to change the chart-type based on the drop-down value. I had tried and followed the example but it still unable to work. I'm not sure which part that i had missed. I am using JavaScript Charts & Graphs from JSON Data Using AJAX. The code below:
<script src="../js/custom.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/>
<script>
window.onload = function () {
var dataPoints = [];
$.getJSON( "<?php echo $url; ?>", function( json ) {
for (var i = 0; i < json.dates.length; i++) {
dataPoints.push({
x: new Date(json.dates[i]),
y: json.values[i]
});
}
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
exportEnabled: true,
theme: "dark2",
title: {
text: "REPORT"
},
axisY: {
title: "Qty"
},
data: [{
type: "column",
//indexLabel: "{y}", //Shows y value on all Data Points
yValueFormatString: "#,### Units",
indexLabelFontColor: "#5A5757",
indexLabelPlacement: "outside",
dataPoints: dataPoints
}]
});
chart.render();
})
.done(function(){
alert("Completed");
})
.fail(function(e){
console.log('error:');
console.error(e);
})
.always(function(){
alert("always runs");
});
}
var chartType = document.getElementById('chartType');
chartType.addEventListener( "change", function(){
for(var i = 0; i < chart.options.data.length; i++){
chart.options.data[i].type = chartType.options[chartType.selectedIndex].value;
}
chart.render();
});
</script>
Drop-down list:
<select id="chartType" class="form-control" name="chartType">
<option value="column">Column</option>
<option value="line">Line</option>
<option value="bar">Bar</option>
<option value="pie">Pie</option>
<option value="doughnut">Doughnut</option>
</select>
Thank you in advance.
It just seems like variable scope issue, you are creating chart inside AJAX but trying to access it outside during changing the chart type, it would have thrown error in Browser Console. I would suggest you to do it outside AJAX and update just dataPoints inside AJAX.
Here is the updated / working code (Sample JSON with just 1 dataPoint is stored in: https://api.myjson.com/bins/18hgaa):
var dataPoints = [];
var chart;
$.getJSON("https://api.myjson.com/bins/18hgaa", function(json){
for (var i = 0; i < json.dates.length; i++) {
dataPoints.push({
x: new Date(json.dates[i]),
y: json.values[i]
});
}
}).done(function(){
chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
exportEnabled: true,
theme: "dark2",
title: {
text: "REPORT"
},
axisY: {
title: "Qty"
},
data: [{
type: "column",
//indexLabel: "{y}", //Shows y value on all Data Points
yValueFormatString: "#,### Units",
indexLabelFontColor: "#5A5757",
indexLabelPlacement: "outside",
dataPoints: dataPoints
}]
});
chart.render();
});
var chartType = document.getElementById('chartType');
chartType.addEventListener( "change", function(){
for(var i = 0; i < chart.options.data.length; i++){
chart.options.data[i].type = chartType.options[chartType.selectedIndex].value;
}
chart.render();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>
<select id="chartType" class="form-control" name="chartType">
<option value="column">Column</option>
<option value="line">Line</option>
<option value="bar">Bar</option>
<option value="pie">Pie</option>
<option value="doughnut">Doughnut</option>
</select>
I have a dropdown with option to select if you want to see domens that are expiring in given date.
But once i pick date i will get pure json code with right result.
This is my form above table
<form method="post" action="{{ action('DomenController#tabela') }}" id="klijent_rok" onchange="document.getElementById('klijent_rok').submit()">
#csrf
<div class="form-group row">
<label for="istice_za" class="ml-md-auto col-form-label text-md-left" style="padding-right: 10px;">Ističu u roku od:</label>
<select name="istice_za" id="istice_za" class="form-control" style="width: 140px" size="1">
<option value="99" #if($istice_za == '99') selected='selected' #endif>-neodređeno-</option>
<option value="7" #if($istice_za == '7') selected='selected' #endif>za 7 dana</option>
<option value="30" #if($istice_za == '30') selected='selected' #endif>za 30 dana</option>
<option value="60" #if($istice_za == '60') selected='selected' #endif>za 60 dana</option>
<option value="istekli" #if($istice_za == 'istekli') selected='selected' #endif>istekli</option>
</select>
Poništite filtere
</div>
</form>
And this is mine controller for server side Datatable
if(!empty($request->istice_za) && $request->istice_za != 99) {
$date = Carbon::now();
$new_date = Carbon::now();
if($request->istice_za != 'istekli') {
if($request->istice_za == 7) {
$istice_za = 7;
$new_date->addDays(7);
}
if($request->istice_za == 30) {
$istice_za = 30;
$new_date->addDays(30);
}
if($request->istice_za == 60) {
$istice_za = 60;
$new_date->addDays(60);
}
$domen = Domen::where('datum_end', '<', $new_date)
->Where('datum_end', '>', $date)
->with('klijent');
}
else {
$domen = Domen::where('datum_end', '<', $date)->with('klijent');
$istice_za = 'istekli';
}
}
else {
$domen = Domen::with('klijent');
$istice_za = 99;
}
return datatables()->of($domen)->make(true);
And these are my routes
Route::get('/lista-domena/tabela', 'DomenController#tabela');
Route::post('/lista-domena/tabela', 'DomenController#tabela');
What am I doing wrong and not getting that data in my table?
For first, your code is not running the query, you need to add ->get() or first() to get the data.
$domen = Domen::where('datum_end', '<', $date)->with('klijent')->get();
Or,
$domen = Domen::with('klijent')->get();
I managed to solve it. The problem was that i didn't send data from select to my controller. I edited my form to be like this:
<form method="post" action="{{ action('DomenController#tabela') }}" id="klijent_rok">
And then added this in script:
$('#klijent_rok').on('change', function(e) {
table.draw();
});
and changed Ajax to this:
ajax: {
url: '/lista-domena/tabela',
data: function ( d ) {
d.istice_za = $('#istice_za').val();
},
}...
Html:
<table id="affected-requirement-table" class="table table-hover table-sm table-bordered">
<!--Table head-->
<thead>
<tr>
<th>Requirements</th>
<th>Effect Type</th>
</tr>
</thead>
<!--Table head-->
<!--Table body-->
<tbody>
<!-- Ajax Load -->
</tbody>
<!--Table body-->
</table>
Jquery
$(document).ready(function () {
var affectedRequirementsTable = $('#affected-requirement-table').DataTable({
"scrollY": "200px",
"scrollCollapse": true,
"paging": false,
processing: true,
serverSide: true,
bFilter: false,
"bInfo": false,
"bPaginate": true,
"ordering": false,
"bLengthChange": false,
ajax: {
url: '{!! \Illuminate\Support\Facades\URL::to("cr/requirements-datatables") !!}'
},
columns: [
{data: 'number'},
{data: 'effect-type'}
],
// "fnCreatedRow" : function (row, data, dataIndex) {
// var div = document.createElement("div");
// $(div).html('<select name= "changeRequest[]" class="form-control effect-type-select" id="mySelect"> <option selected="selected" value="None">None</option> <option value="Addition">Addition</option> <option value="Deletion">Deletion</option> </select>');
// $(row).children("td:last-child").append(div);
// }
});
// draw the table
affectedRequirementsTable.draw();
$("#affected-requirement-table").on('change',".effect-type-select",function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
console.log(valueSelected);
});
})
routes:
Route::get('cr/requirements-datatables', "ChangeRequestController#requirementsAndEffectTypesDatatables");
Controller:
public function requirementsAndEffectTypesDatatables(ChangeRequests $request)
{
$changeRequest = DB::table('requirement')->select(['number','id']);
return DataTables::of($changeRequest)->addColumn('effect-type', function ($changeRequest) {
return '
<select name= "changeRequest[]" class="form-control effect-type-select" id="mySelect">
<option selected="selected" value="None">None</option>
<option value="Addition">Addition</option>
<option value="Deletion">Deletion</option>
</select>';
})->rawColumns(['effect-type'])->make(true);
}
I am using FullCalendar 3.1.0 plugin to show events. I was able to implement multiple events with a dropdown. But user is only able to select 1 option from a single dropdown filter. My goal is to give the opportunity to select multiple options in a each dropdown filter. I am using dropdown. But when I hold down CTR and click on options, it only shows events for the first option in the list. Any help would be greatly appreciated.
Here is the HTML:
<!-- Main view: Title and calendar -->
<div class="container">
<div class="row">
<div class="col-xs-12">
<h1 id="cal_title">Change Calendar</h1>
<div class="search_bar">
<ul id="menu">
Search By:
<li>
<select id="status_selector" multiple>
<option value="all" selected="selected">Status Types - All</option>
</select>
</li>
<li>
<select id="group_selector" multiple>
<option value="all" selected="selected">Group - All</option>
</select>
</li>
<li>
<select id="changeType_selector" multiple>
<option value="all" selected="selected">Type of Change - All</option>
<option value="6250">Emergency Change</option>
<option value="6882">Expedited Change</option>
<option value="6249">Normal Change</option>
<option value="9999">Standard Change</option>
</select>
</li>
<li>
<select id="downtime_selector" multiple>
<option value="all" selected="selected">Downtime - All</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</li>
</ul>
</div>
<div id="calendar"></div>
<div id="footer">To ensure optimal performance, only changes created in the past 90 days are shown. For changes older than 90 days please reference EasyVista. <br />If an issue has been found and/or you have a recommendation, please open a ticket for Service Request/Applications/EasyVista - Other Request, explaining the issue or recommendation.</div>
<div id="version">SACC v2.0</div>
</div>
</div>
</div>
Here is my Javascript:
$(document).ready(function() {
/* Find all the distinct STATUS_EN and place them into a dropdown list */
// This creates first 2 dropdown dynamically
$.getJSON('json/events.json',function(json){
var usedStatus = []; // Array to keep track of all STATUS_EN that have been seen
var usedGroup = []; // Array to keep track of all group_selector that have been seen
// For each object, store the status/group in predefined variables
$.each(json, function(i,v){
// If STATUS_EN has not been seen
if (usedStatus.indexOf(v.STATUS_EN) == -1){
usedStatus.push(v.STATUS_EN); // Add STATUS_EN to usedStatus
}
// If responsible_group has not been seen
if (usedGroup.indexOf(v.responsible_group) == -1){
usedGroup.push(v.responsible_group); // Add responsible_group to usedStatus
}
});
// Sort both array variables in alphabetical order.
usedStatus.sort();
usedGroup.sort();
// Create the dropdown
usedStatus.forEach(function(value){
if (value != undefined){ // If STATUS_EN is not undefined
$("#status_selector").append('<option value="'+value+'">'+value+'</option>'); // Create an option for the dropdown list
}
});
usedGroup.forEach(function(value){
if (value != undefined){ // If responsible_group is not undefined
$("#group_selector").append('<option value="'+value+'">'+value+'</option>'); // Create an option for the dropdown list
}
});
});
/* If end_date is null, return start_date */
function isNull(end_date,start_date){
if(end_date !== null){
return end_date;
} else {
return start_date;
}
}
/* Calendar structure */
$('#calendar').fullCalendar({
/* Theme enabler */
theme: false,
/* Header description */
header: {
left: 'prev,today,next',
center: 'title',
right: 'month,basicWeek,basicDay'
},
/* Set the default view to Day */
defaultView: 'basicWeek',
/* Arrow stype (Used when theme is enabled) */
themeButtonIcons: {
prev: 'circle-triangle-w',
next: 'circle-triangle-e'
},
/* Text to show in the button */
buttonText: {
today: 'Today',
month: 'Month',
week: 'Week',
day: 'Day',
list: 'Week List'
},
navLinks: true, // Can click day/week names to navigate views
editable: false, // Remove permission to move events
eventLimit: true, // Allow "more" link when too many events
businessHours: true, // grayout afterhours
multiple: true,
/* Function that allows user to click on event. */
eventClick: function (event, jsEvent, view) {
//set the values and open the modal
$('#modalTitle').html(event.title);
$('#modalBody').html(event.text);
$('#eventUrl').attr('href', event.url);
$('#eventStatus').html("Status: " + event.STATUS_EN);
$('#fullCalModal').modal('show');
return false; // prevent from going to EasyVista right away
},
/* Function that shows description when hovering over event */
eventMouseover: function (data, event, view) {
tooltip = '<div class="tooltiptopicevent">'
+ '<strong>Request Number:</strong> ' + data.RFC_NUMBER
+ '<br /><strong>Status:</strong> ' + data.STATUS_EN
+ '<br /><strong>Start Date:</strong> ' + moment(data.start).format("MM/D, h:mm:ss a")
+ '<br /><strong>End Date:</strong> ' + moment(isNull(data.end,data.start)).format("MM/D, h:mm:ss a")
+ '<br /><strong>Description:</strong> ' + data.text + '</div>';
$("body").append(tooltip);
$(this).mousemove(function(event){
$(".tooltiptopicevent").position({
my: "left+3 bottom-3",
of: event,
collision: "flipfit"
});
});
},
/* Hide description when mouse moves out */
eventMouseout: function (data, event, view) {
$(this).css('z-index', 8);
$('.tooltiptopicevent').remove();
},
/* Feed in events from JSON file through PHP */
events: {
url: 'php/get-events.php'
},
/* Render the events */
eventRender: function eventRender(event, element, view){
return['all',event.STATUS_EN].indexOf($('#status_selector option:selected').val()) >= 0
&& ['all',event.responsible_group].indexOf($('#group_selector option:selected').val()) >= 0
&& ['all',event.change_type].indexOf($('#changeType_selector option:selected').val()) >= 0
&& ['all',event.downtime].indexOf($('#downtime_selector option:selected').val()) >= 0
},
/* Show status loading when loading */
loading: function(bool) {
$('#loading').toggle(bool);
}
});
/* Call on fullCalendar after selection of dropdown option
$('#status_selector, #group_selector, #changeType_selector, #downtime_selector').change(function() {
$('#calendar').fullCalendar('rerenderEvents');
//$('#calendar').fullCalendar('refetchEvents'); // this allows the spinner to come up each time filter is changed.
});*/
/**/
$('#status_selector, #group_selector, #changeType_selector, #downtime_selector').on('change',function(){
$('#calendar').fullCalendar('rerenderEvents');
});
});
Sample of how my .json file looks like:
[
{
"start": "2016-12-2T17:0:00",
"end": "2016-12-2T17:0:00",
"title": "12/2/2016 5:00 PM - group1",
"url": "https://sample.com",
"text": "some needed text",
"description": "description of event",
"REQUEST_ID": 462820,
"STATUS_EN": "Open",
"downtime": "No",
"change_type": "9999",
"responsible_group": "group1",
"RFC_NUMBER": "C201612_09454"
},
{
"start": "2017-2-1T21:0:00",
"end": "2017-2-1T21:0:00",
"title": "2/1/2017 9:00 PM - group2",
"url": "https://samplesite.com",
"text": "some text",
"description": "description of event",
"REQUEST_ID": 521157,
"STATUS_EN": "Closed",
"downtime": "No",
"change_type": "6250",
"responsible_group": "group2",
"RFC_NUMBER": "C201702_00976"
}
]
Doing .val() on a group of selected elements (e.g. your $('#status_selector option:selected').val()) will only return the value from the first matched element - as per the very first line of the docs: http://api.jquery.com/val/
So you need to loop through and check the values of all the selected options, and test for them individually. Something like this (untested):
eventRender: function eventRender(event, element, view){
var statusMatch = false;
var statusArr = ['all',event.STATUS_EN];
$('#status_selector option:selected').each(function(index, el)
{
if (statusArr.indexOf($(this).val()) > = 0) statusMatch = true;
});
var groupMatch = false;
var groupArr = ['all',event.responsible_group];
$('#group_selector option:selected').each(function(index, el)
{
if (groupArr.indexOf($(this).val()) > = 0) groupMatch = true;
});
var changeMatch = false;
var changeArr = ['all',event.change_type];
$('#changeType_selector option:selected').each(function(index, el)
{
if (changeArr.indexOf($(this).val()) > = 0) changeMatch = true;
});
var downtimeMatch = false;
var downtimeArr = ['all',event.downtime];
$('#downtime_selector option:selected').each(function(index, el)
{
if (downtimeArr.indexOf($(this).val()) > = 0) downtimeMatch = true;
});
return (statusMatch && groupMatch && changeMatch && downtimeMatch);
}
I have the code below that will change a state dropdown list when you change the country list.
How can I make it change the state list ONLY when country ID number 234 and 224 are selected?
If another country is selected it should be change into this text input box
<input type="text" name="othstate" value="" class="textBox">
The form
<form method="post" name="form1">
<select style="background-color: #ffffa0" name="country" onchange="getState(this.value)">
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>
<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>
The javascript
<script>
function getState(countryId)
{
var strURL="findState.php?country="+countryId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
// only if "OK"
if (req.status == 200)
{
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
Just check the countryId value before you do the AJAX request and only perform the request if the countryId is in the allowable range. In the case where the countryId doesn't match, I would hide the select (probably clear it's value, too) and show an already existing input that was previously hidden. The reverse should be done if an allowable country is chosen.
jQuery example below:
<form method="post" name="form1">
<select style="background-color: #ffffa0" name="country" onchange="getState(this.value)">
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>
<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>
<input type="text" name="othstate" value="" class="textBox" style="display: none;">
</form>
$(function() {
$('#country').change( function() {
var val = $(this).val();
if (val == 223 || val == 224) {
$('#othstate').val('').hide();
$.ajax({
url: 'findState.php',
dataType: 'html',
data: { country : val },
success: function(data) {
$('#state').html( data );
}
});
}
else {
$('#state').val('').hide();
$('#othstate').show();
}
});
});
I think the simple thing to do is to provide a state dropdown and a text entry box with different ids. Set the display of both to none and then you just need to surround your contents of getState() with
if (countryId == 233 || countryId == 234) {
/* Ajax state population here */
dropdownId.display = 'block';
textEntryId.display = 'none';
}
else {
textEntryId.display = 'block';
dropdownId.display = 'none';
}
(where dropdownId and textEntryId are the ids of the relevant UI components) so you enable/display the display for the state dropdown or the text entry upon selection.
JQuery is all well and good, but I wouldn't introduce it just to solve this problem.
EDIT: here is a solution that works quite well for the task, adapting the lines of Tvanfosson:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
</script>
<script>
$(function() {
$('#country').change( function() {
var val = $(this).val();
if (val == 223 || val == 224) {
$('#othstate').val('').hide();
$.ajax({
url: 'findState.php',
dataType: 'html',
data: { country : val },
success: function(data) {
$('#state').html( data );
}
});
}
else {
$('#state').val('').hide();
$('#othstate').show();
}
});
});
</script>
<select style="background-color: #ffffa0" name="country" id=country >
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>
<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>
<input type="text" name="othstate" id=othstate value="" class="textBox" style="display: none;">
As you can see, I eliminated the <form> element which is not absolutely necessary but can be added (and then has to be used properly in case JS is deactivated at the users end. See
here.
I also eliminated the onchange event which is being replaced by the 'change()` jquery function.
**index.html**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Populate City Dropdown Using jQuery Ajax</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "ajaxServer.jsp",
data: { country : selectedCountry }
}).done(function(data){
$("#response").html(data);
});
});
});
</script>
<style>
select { width: 10em }
</style>
</head>
<body>
<form>
<table>
<tr>
<td> <label>Country:</label></td>
<td> <select class="country">
<option>Select</option>
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
</select>
</td>
</tr>
<tr><td >
<label>States:</label></td>
<td> <select id="response">
<option>Select State</option>
</select>
</td></tr>
</table>
</form>
</body>
</html>
**ajaxServer.jsp**
<option>Select State</option>
<%
String count=request.getParameter("country");
String india[]={"Mumbai", "New Delhi", "Bangalore"};
String usa[]={"New Yourk", "Los Angeles","California"};
String uk[]={"London", "Manchester", "Liverpool"};
String states[];
if(count.equals("india"))
{
for(int i=0;i<=2;i++)
{
out.print("<option>"+india[i]+"</option>");
}
}
else if(count.equals("usa"))
{
for(int i=0;i<usa.length;i++)
{
out.print("<option>"+usa[i]+"</option>");
}
}
else if(count.equals("uk"))
{
for(int i=0;i<=2;i++)
{
out.print("<option>"+uk[i]+"</option>");
}
}
%>
VK API just select country , get it id and select city from
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
var $j = jQuery.noConflict();
var _getCountry = function() {
$j.ajax({
url: "http://api.vk.com/method/database.getCountries",
data: {
'v': 5.5,
'need_all': 0,
'code' : 'RU,UA,BY,KZ,KG,LV,EE'
// 'count': 10
},
dataType: 'jsonp',
success: function(data, status) {
if (status !== 'success') {
return false;
}
console.log(data.response, status);
$j.each(data.response.items, function(i, item) {
console.log("each country");
var newOption = '<option id="' + item.id + '" value="' + item.title + '">' + item.title + '</option>';
country_options.push(newOption);
});
document.getElementById('countrylist').innerHTML = country_options;
}
});
}
var _getCity = function(country_id) {
$j.ajax({
url: "http://api.vk.com/method/database.getCities",
data: {
'v': 5.61,
'need_all': 0,
'country_id': country_id
},
dataType: 'jsonp',
success: function(data, status) {
if (status !== 'success') {
return false;
}
console.log(data.response, status);
$j.each(data.response.items, function(i, item) {
console.log("each city");
var newOption = '<option id="' + item.id + '" value="' + item.title + '">' + item.title + '</option>';
city_options.push(newOption);
});
document.getElementById('citylist').innerHTML = city_options;
}
});
}
var city_options = [];
var country_options = [];
$j(document).ready(function () {
_getCountry();
$j('#country').on('input',function() {
var opt = $j('option[value="'+$j(this).val()+'"]');
var countryid = opt.attr('id');
_getCity(countryid);
});
});
</script>
<div class="form-group">
<label class="col-lg-4 control-label">Страна:</label>
<div class="col-lg-8">
<div class="controls">
<input name="country" list="countrylist" id="country" class="form-control" />
<datalist id="countrylist">
</datalist>
</div>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label">Город:</label>
<div class="col-lg-8">
<input name="city" list="citylist" id="city" class="form-control"/>
<datalist id="citylist">
</datalist>
</div>
</div>
////////////////// connection file con.php rishabh
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db( 'testajax' );
?>
/////////////////////////// index.php rishabh
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<?php
include('con.php');
?>
<form>
<div class="frmDronpDown">
<div class="row">
<table><tr><td><label>Country:</label><br/>
<select name="country" id="country" data-name="country" class="demoInputBox" onChange="getCountry(this.value);">
<option value="">Select Country</option>
<?php
$sql = mysql_query("SELECT distinct country FROM statecont ");
while($result=mysql_fetch_array($sql)){
?>
<option value="<?php echo $result['country']; ?>"><?php echo $result['country']; ?></option>
<?php
}
?>
</select> </td>
<td>
<label>Phone:</label><br/>
<select name="phone" id="phone" data-name="phone" class="demoInputBox" onChange="getPhone(this.value);">
<option value="">Select Country</option>
<?php
$sql = mysql_query("SELECT distinct phone FROM statecont ");
while($result=mysql_fetch_array($sql)){
?>
<option value="<?php echo $result['phone']; ?>"><?php echo $result['phone']; ?></option>
<?php
}
?>
</select>
</td></tr></table>
</div>
<div id="state-list"></div>
</div>
</form>
<script>
function getCountry(val) {
var dataname = $('#country').attr('data-name');
console.log(dataname);
$.ajax({
type: "POST",
url: "data.php",
data: {
value_name: val,
colomn_name: dataname
},
success: function (data){
$("#state-list").html(data);
}
});
}
function getPhone(val) {
var dataname = $('#phone').attr('data-name');
console.log(dataname);
$.ajax({
type: "POST",
url: "data.php",
data: {
value_name: val,
colomn_name: dataname
},
success: function (data){
$("#state-list").html(data);
}
});
}
</script>
// ////////////////////data file data.php rishabh
<?php
$val = $_POST["value_name"];
$colomn = $_POST["colomn_name"];
include('con.php');
$sql_aa = mysql_query("SELECT * FROM statecont where ".$colomn."='$val'"); ?>
<table>
<tr><td>State</td><td>Countery</td></tr>
<?php while($result_aa=mysql_fetch_array($sql_aa)){ ?>
<tr><td><?php echo $result_aa['state']; ?></td><td><?php echo $result_aa['country']; ?></td></tr>
<?php } ?>
</table>