I am new to angularjs. I'm trying to write code to get content from multiple select options. As per my below code, I want to get #html content when I select "HTML 5 FEATURES" from Product drop down.How can I get in simpler way. Here is what my Code looks like:
enter code here
<html>
<head>
<link rel="stylesheet"
href= "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/
css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/
angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<div class="container">
<h1>Web Developer</h1>
<div class="row">
<div class="col col-lg-4">
<form class="form">
<div class="form-group">
<label> Categories :</label>
<select name="categoriesList" ng-model="selectedCategory"
class="form-control">
<option ng-repeat="item in CategoryList"
value='{{item}}'>{{item.value}}</option>
</select>
</div>
<div class="form-group">
<label> Products :</label>
<select ng-disabled="selectedCategory == null"
name="productList" ng-model="selectedProduct"
class="form- control">
<option ng-repeat="item in ProductList | myFilter :
selectedCategory" value='{{item}}'>{{item.value}}</option>
</select>
</div>
<div id="html" ng-if="selectedProduct.value === 'HTML 5 FEATURES'">
<div class="newFeatures">
<ul>
<li>New Doctype</li>
<li>The Figure Element</li>
<li>Email Inputs</li>
<li>Placeholders</li>
<li>Local Storage</li>
<li>Autofocus Attribute</li>
</ul>
</div>
</div>
</form>
</div>
</div>
<script>
var app = angular.module('myApp', []);
angular.module('myApp').filter('myFilter', function() {
return function(input, selectedCategory) {
input = input || '';
if(selectedCategory == null){
return input;
}else{
var out = new Array();
selectedCategory = JSON.parse(selectedCategory);
for (var i = 0; i < input.length; i++) {
var item = input[i];
if(item.categoryId == selectedCategory.id){
out.push(item);
}
}
return out;
}
};
});
app.controller('myCtrl', ['$scope', function($scope) {
$scope.selectedCategory = null;
$scope.selectedProduct = null;
$scope.CategoryList = [
{id:0, value:'HTML'},
{id:1, value:'CSS'},
{id:2, value:'JAVA SCRIPT'},
{id:3, value:'ANGULAR JS'}
];
$scope.ProductList = [
{categoryId:0, id:1, value:'HTML 5 FEATURES'},
{categoryId:0, id:2, value:'WEB WORKERS'},
{categoryId:0, id:3, value:'STORAGE'},
{categoryId:0, id:3, value:'CANVAS'},
{categoryId:0, id:3, value:'KEYFRAMES'},
{categoryId:1, id:4, value:'BOX MODEL'},
{categoryId:1, id:5, value:'NEW CSS3 FEATURES'},
{categoryId:1, id:6, value:'POSITIONS'},
{categoryId:2, id:7, value:"OOPs"},
{categoryId:2, id:8, value:'ARRAY MANIPULATIONS'},
{categoryId:2, id:9, value:'EMAIL'},
{categoryId:3, id:9, value:'DIRECTIVES'},
{categoryId:3, id:9, value:'FILTERS'},
{categoryId:3, id:9, value:'SCOPES & ROOT SCOPES'},
];
}]);
</script>
</body>
</html>
Simple way - for example put $http.get request into you controller and set ProductList data.
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
$scope.ProductList = response.data;
}, function errorCallback(response) {
});
Related
I made an autocomplete component and it works well in Chrome, but not in IE and Safari.
It displays the template twice in IE and Safari. It works but it shows the template in addition to the rendered HTML. See the image.
What did I do wrong?
<div id="main">
<autocomplete></autocomplete>
</div>
<template id="autocomplete">
<div>
<div class="col">
<section class="box clr1">
<div>
<div>
<input type="text" placeholder="Welk product zoekt U?" v-model="query" v-on:keyup="autoComplete" class="form-control">
<div class="panel-footer" v-if="results.length">
<ul class="list-group">
<li class="list-group-item" v-for="result in results">
<span style="text-decoration: underline;cursor:pointer" v-on:click="showDetail(result.id)">#{{ result.title }}</span>...
<div class="col">
<section class="box clr1">
<div>
<div v-for="detail in resultdetail">
<h1>#{{ detail.title }}</h1>
<h2>#{{ detail.page_title }}</h2>
<p v-html="detail.description"></p>...
Vue.component('autocomplete', {
template: '#autocomplete',
data: function () {
return {
show: false,
query: '',
results: [],
resultdetail: []
}
},
methods: {
autoComplete: function () {
this.results = [];
if (this.query.length > 1) {
axios.get('/getproductjson/' + this.query + '/0')
.then(function (response) {
this.results = response.data
}.bind(this))...
showDetail: function (productId) {
if (productId > 0) {
this.show = true;
this.resultdetail = [];
axios.get('/getproductjson/loremipsumdipsum/'+productId)
.then(function (response) {
this.resultdetail = response.data
}.bind(this))...
}
});
new Vue({
el: '#main'
});
Result:
Internet explorer does not support the template tag.
What you're seeing in Internet Explorer is your instantiated Vue, and, since IE doesn't implement template it just shows your template on screen.
In IE if you want to store your template in the DOM you typically have to use the a script template.
<script type="text/x-template" id="autocomplete">
...
</script>
Im trying to filter divs by data attribute rather than class using isotope... im not sure how isotope works and there appears to be nothing in the documentation that references filtering data attributes and not just classes?!
Im sure i will slap my self with the answer...
but this is as far as I have got:
var $grid = $('.isotope').isotope({
itemSelector: '.isotope-item'
});
$('#item-filter-select').on('change', function () {
var el = this.value;
$grid.isotope({ filter: el });
});
<div id="filters">
<h4>Geschenkideen</h4>
<select id="item-filter-select">
<option value="*" >Show All</option>
<option value="clothes" >Clothing</option>
<option value="jewelry" >Jewelry</option>
<option value="misc" >Miscellaneous</option>
</select>
</div>
<div class="isotope">
<div class="isotope-item" data-price="23" data-type="misc">
<img src="http://unit60.com/vendo/img/shop/1.jpg" />23
</div>
<div class="isotope-item" data-price="400" data-type="misc">
<img src="http://unit60.com/vendo/img/shop/2.jpg" />400
</div>
<div class="isotope-item" data-price="12" data-type="jewelry">
<img src="http://unit60.com/vendo/img/shop/3.jpg" />12
</div>
<div class="isotope-item clothes" data-price="8" data-type="clothes">
<img src="http://unit60.com/vendo/img/shop/4.jpg" />8
</div>
<div class="isotope-item" data-price="144" data-type="misc">
<img src="http://unit60.com/vendo/img/shop/5.jpg" />144
</div>
<div class="isotope-item" data-price="70" data-type="misc">
<img src="http://unit60.com/vendo/img/shop/6.jpg" />70
</div>
<div class="isotope-item" data-price="445" data-type="jewlery">
<img src="http://unit60.com/vendo/img/shop/3.jpg" />445
</div>
<div class="isotope-item" data-price="64" data-type="misc">
<img src="http://unit60.com/vendo/img/shop/2.jpg" />64
</div>
<div class="isotope-item" data-price="21" data-type="misc">
<img src="http://unit60.com/vendo/img/shop/5.jpg" />21
</div>
<div class="isotope-item" data-price="82.50" data-type="misc">
<img src="http://unit60.com/vendo/img/shop/1.jpg" />82.50
</div>
<div class="isotope-item" data-price="25" data-type="jewelry">
<img src="http://unit60.com/vendo/img/shop/3.jpg" />25
</div>
<div class="isotope-item" data-price="100" data-type="misc">
<img src="http://unit60.com/vendo/img/shop/6.jpg" />100
</div>
<div class="isotope-item" data-price="30" data-type="misc">
<img src="http://unit60.com/vendo/img/shop/2.jpg" />30
</div>
</div>
codepen:
http://codepen.io/unit60/pen/vXyAzj
HELLLLP!!! :)
ok... I have one answer that works, probably not the most elegant but here we go:
var $grid = $('.isotope').isotope({
itemSelector: '[data-type]'
});
$('#item-filter-select').change( function () {
var el = this.value;
var fel;
if(el!='*'){
fel = "[data-type='" + el + "']"
}else{
fel = "*"
}
$grid.isotope({ filter: fel });
});
Yay... I changed the code a bit so that I could combine filters:
var filters = {};
$('.item-filter-select').on( 'change',function() {
var $this = $('option:selected');
var $parent = $(this);
var level = $(this).parent().find('select option:selected');
// get group key
var $buttonGroup = $parent.parents('.select-group');
var filterGroup = $buttonGroup.attr('data-filter-group');
// set filter for group
filters[ filterGroup ] = level.data('value');
// combine filters
var filterValue = concatValues( filters );
$grid.isotope({ filter: filterValue });
});
// flatten object by concatting values
function concatValues( obj ) {
var value = '';
for ( var prop in obj ) {
value += obj[ prop ];
}
return value;
}
Updated codepen: http://codepen.io/unit60/pen/ORbdWE
I was to export a handsontable to XLS file but i encountered this bug:
The result excel file contains 2 table like this:
First name Last name Email Phone Password
23123 31231231 213#dsfsd213.563 NjU0NTY0 46565465546
Buu Mr your#email.com MTI0NTU1 your password
First name Last name Email Phone Password
In the code box below is my code in jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<script src="resources/handsontable/handsontable.full.js"></script>
<link rel="stylesheet" media="screen" href="resources/handsontable/handsontable.full.css">
<link rel="stylesheet" media="screen" href="resources/handsontable/github.css">
<div class="tab-pane active" id="user">
<!-- <form action="addBatchUser" method="POST"> -->
<div class="col-lg-12">
<div class="page-header">
<h4>
<span>Export to Excel</span>
</h4>
</div>
<div class="panel-body">
<div class="form-group">
<label class="col-lg-2 control-label">Parent Group</label>
<div class="col-lg-10">
<input type="text" readonly id="parentGroupUser" class="form-control uniform-input text focus"></input> <input
type="hidden" id="group-parent" name="groupou"></input>
</div>
</div>
<br />
<div class="form-group">
<!-- Space line -->
<div class="col-lg-12">
<div class="col-lg-2">
<label class="control-label"></label>
</div>
<div class="col-lg-10"></div>
</div>
<div class="col-lg-2">
<label class="control-label"></label>
</div>
<div class="col-lg-10">
<div id="example"></div>
<br /> <input type="button" value="Export" id="btnExport" class="btn btn-success" />
<div>
<img id="access_log_print" src="resources/images/ajax-loader.gif" />
</div>
</div>
</div>
</div>
</div>
<!-- </form> -->
</div>
<div id="resViewer"></div>
<script language="JavaScript" type="text/javascript">
$(document).ready(
function() {
$("#btnExport").click(
function(e) {
window.open('data:application/vnd.ms-excel,'
+ encodeURIComponent($('div[id$=example]')
.html()));
e.preventDefault();
});
});
$(document).ready(
function() {
hideLoadingMsg();
function showLoadingMsg() {
$("input[type=submit]").attr("disabled", "disabled");
$('#access_log_print').show();
}
function hideLoadingMsg() {
$("input[type=submit]").removeAttr("disabled");
$('#access_log_print').hide();
}
var data = ${listuser}
;
var container = document.getElementById('example');
var hot = new Handsontable(container, {
data : data,
rowHeaders : false,
colHeaders : true,
// contextMenu : true,
colHeaders : [ 'First name', 'Last name', 'Email', 'Phone',
'Password' ],
colWidths : [ 130, 130, 150, 120, 130 ],
columns : [ {
data : "firstName",
readOnly : true
}, {
data : "lastName",
readOnly : true
}, {
data : "email",
readOnly : true
}, {
data : "telNumber",
readOnly : true
}, {
data : "password",
readOnly : true
} ]
});
// var hot ={}
// $("#save")
// .click(
// function() {
// var json = container
// .handsontable('getData');
// var jsonData = createJsonSection(json);
// if (jsonData === null) {
// return false;
// } else {
// showLoadingMsg();
// var dataJson = JSON
// .stringify(jsonData);
// console.log(dataJson);
// $
// .ajax({
// url : "addBatchUser",
// data : {
// "data" : dataJson,
// "groupou" : $(
// '#group-parent')
// .val(),
// "saveToLdap" : $(
// '#saveToLdap')
// .is(
// ':checked'),
// "saveToSvnAcm" : $(
// '#saveToSvnAcm')
// .is(
// ':checked'),
// "svnAcmGroup" : $(
// '#svnAcmGroup')
// .val()
// }, //returns all cells' data
// type : "POST",
// success : function(
// res) {
// $("#resViewer")
// .empty();
// $("#resViewer")
// .append(
// res);
// hideLoadingMsg();
// }
// });
// }
// });
});
</script>
I recommend you don't export to CSV using the html content of the table you see but rather use the data itself to parse and export correctly. The problem with your method is that Handsontable is rendering a floating "headers" row used to display the header at the bottom. If you still want to use this method, you could simply parse this html and remove the last line.
I have a very simply page at the moment. It has a first name input, last name input, and a list of names added. You can add your first and last name to the text box, press add. It adds it the peopleList I have and adds a new listItem with their name.
My issue is when I add to the peopleList in my code, it does not update the listView. I think I need to use observable, but I am not exactly sure how to do it. My list shows it has 25 items added to it after I click btnMany, which is how many it show have.
here is the body of my code:
<!--Load Some Data-->
<div id="peopleDefaultView"
data-role="view"
data-model="ViewModel"
data-layout="default">
<!--View-->
<input type="text" data-bind="value: firstName" id="fName" />
<input type="text" data-bind="value: lastName" id="lName" />
<a data-bind="click: addName" data-role="button" id="btnOne">Add</a>
<a data-bind="click: setValues" data-role="button" id="btnMany">Add Many</a>
<div style="margin-top: 10px">
People List:
<ul data-template="people-l-template" data-bind="source: peopleList" id="pList"></ul>
</div>
</div>
<!-- Kendo Template-->
<script id="people-l-template" type="text/x-kendo-template">
<li>
FirstName: <span data-bind="text: first"></span>
LastName: <span data-bind="text: last"></span>
<a data-bind="click: removeName" data-role="button" id="btnRemoveName">X</a>
</li>
</script>
And here is my script to go along with it
<script>
var ViewModel = {
firstName: '',
lastName: '',
peopleList: [],
addName: function (e) {
this.get("peopleList").push({
first: this.get("firstName"),
last: this.get("lastName"),
});
this.set("firstName", '');
this.set("lastName", '');
},
removeName: function (e) {
this.set("peopleList", jQuery.grep(this.peopleList, function (item, i) {
return (item.firstName != e.data.firstName && item.lastName != e.data.lastName);
}));
},
setValues: function (e) {
GetValueFromServer();
}
};
var GetValueFromServer = function () {
$.ajax({
type: "GET",
url: "GetPeopleService.svc/GetPersonById/",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
response.forEach(function (person) {
ViewModel["peopleList"].push({
first: person.firstName,
last: person.lastName
});
});
alert(ViewModel.peopleList.length);
},
error: function (response) {
console.log(response);
}
});
};
var application = new kendo.mobile.Application(document.body);
</script>
There were a few things wrong with the code you provided, the most notably being that you didn't set the role for your <ul> element. You need to change it to have the attribute data-role="listview". You also can't use an <li> element as the root element for a listview template (KendoUI automatically takes care of this for you), otherwise you'll get an error when the list is bound.
Here's an example on JS Bin.
And here's the code:
<!--Load Some Data-->
<div id="peopleDefaultView"
data-role="view"
data-model="viewModel"
data-layout="flat">
<!--View-->
<input type="text" data-bind="value: firstName" id="fName" />
<input type="text" data-bind="value: lastName" id="lName" />
<a data-bind="click: addName" data-role="button" id="btnOne">Add</a>
<div style="margin-top: 10px">
People List:
<ul id="pList"
data-role="listview"
data-template="people-l-template"
data-bind="source: peopleList">
</ul>
</div>
</div>
<!-- Kendo Template-->
<script id="people-l-template" type="text/x-kendo-template">
FirstName: <span>#:first#</span>
LastName: <span>#:last#</span>
<a id="btnRemoveName"
data-role="button"
data-bind="click: removeName"
data-first="#:first#" data-last="#:last#">
X
</a>
</script>
...
var viewModel = {
firstName: null,
lastName: null,
peopleList: [],
addName: function (e) {
var me = this;
me.get('peopleList').push({
first: me.get('firstName'),
last: me.get('lastName')
});
me.set('firstName', '');
me.set('lastName', '');
},
removeName: function (e) {
var me = this;
me.set('peopleList', $.grep(me.peopleList, function (item, i) {
return item.first != e.target.data('first')
&& item.last != e.target.data('last');
}));
}
};
var application = new kendo.mobile.Application(document.body);
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>