Directive's code fires before I got data - javascript

This is continuation of this question Get other columns from select ng-options
I have the problems with my directive. First problem is that with the very first initial load of the form I can see correctly department and category, but item shows 'Select Item' instead of the item. The second problem is when I navigate to another row in the list, the initial values are not shown (e.g. everything is showing 'Select Department', 'Select Category', 'Select Item' instead of the values. I confirmed that in that situation I didn't retrieve the row's data yet. So, I need to run directive's code only after I got my data.
How can I resolve my problems?
Here is the whole code for the directive:
(function () {
'use strict';
var app = angular.module('sysMgrApp');
app.directive('smDci', ['departmentService', 'categoryService', 'itemService', smDci]);
function smDci(departmentService, categoryService, itemService) {
var directive = {
restrict: 'E',
scope: {
selectedDepartmentId: '=?departmentid',
selectedCategoryId: '=?categoryid',
selectedItemId: '=itemid',
selectedDci: '=?dci'
},
controller: ['$scope', 'departmentService', 'categoryService', 'itemService',
function ($scope, departmentService, categoryService, itemService) {
$scope.selectedDepartmentId = $scope.selectedDepartmentId || 0;
$scope.selectedCategoryId = $scope.selectedCategoryId || 0;
$scope.selectedItemId = $scope.selectedItemId || 0;
$scope.selectedDci = $scope.selectedDci || '';
var init = function () {
$scope.metaData = {};
window.console && console.log('Selected departmentId = ' + $scope.selectedDepartmentId +
' Selected categoryId = ' + $scope.selectedCategoryId + ' Selected ItemId = ' + $scope.selectedItemId);
departmentService.getAllDepartments().then(function (data) {
$scope.metaData.departments = data.departments;
//window.console && console.log('Got all departments...')
});
if ($scope.selectedDepartmentId == 0 && $scope.selectedCategoryId == 0 && $scope.selectedItemId != 0) {
itemService.getItemById($scope.selectedItemId).then(function (data) {
var item = data.item;
if (item != null) {
$scope.selectedItem = item;
$scope.selectedDepartmentId = item.departmeId;
$scope.selectedCategoryId = item.categoryId;
window.console && console.log('Initial selections are about to fire...')
getInitialSelections();
}
});
}
else {
getInitialSelections();
}
};
var getInitialSelections = function()
{
if ($scope.selectedDepartmentId != 0) {
$scope.departmentChanged($scope.selectedDepartmentId);
}
if ($scope.selectedCategoryId != 0) {
$scope.categoryChanged($scope.selectedCategoryId);
}
}
$scope.departmentChanged = function (departmentId) {
if (!departmentId) {
$scope.selectedCategoryId = '';
$scope.selectedItemId = '';
$scop.selectedItem = {};
$scope.selectedDci = '';
}
else
{
categoryService.getCategoriesByDepartmentId(departmentId).then(function (data) {
$scope.metaData.categories = data.categories;
//window.console && console.dir($scope.selectedItem);
});
}
};
$scope.categoryChanged = function (categoryId) {
if (!categoryId) {
$scope.selectedItemId = '';
$scope.selectedItem = null;
$scope.selectedDci = '';
}
else
{
itemService.getItemsByCategoryId(categoryId).then(function (data) {
$scope.metaData.items = data.items;
});
}
};
$scope.itemChanged = function(item)
{
$scope.selectedItemId = item.itemId;
$scope.selectedDci = item.department + item.category + item.item;
}
init();
}],
templateUrl: 'app/templates/smDci'
};
return directive;
}
})();
and its HTML:
<div class="row">
<label class="control-label col-md-2" title="#Labels.dci">#Labels.dci:</label>
<div class="col-md-3">
<select class="form-control" ng-model="selectedDepartmentId" name="department" id="department"
ng-options="d.departmeId as d.descrip for d in metaData.departments"
data-no:dirty-check
ng-change="departmentChanged(selectedDepartmentId)">
<option value="">#String.Format(Labels.selectX, Labels.department)</option>
</select>
</div>
<div class="col-md-3">
<select class="col-md-3 form-control" ng-model="selectedCategoryId" id="category" name="category"
ng-disabled="!selectedDepartmentId"
data-no:dirty-check
ng-change="categoryChanged(selectedCategoryId)"
ng-options="c.categoryId as c.descrip for c in metaData.categories | filter: {departmeId:selectedDepartmentId}">
<option value="">#String.Format(Labels.selectX, Labels.category)</option>
</select>
</div>
<div class="col-md-3">
<select class="col-md-3 form-control" ng-model="selectedItem" id="item" name="item"
ng-disabled="!selectedCategoryId"
ng-change="itemChanged(selectedItem)"
ng-options="c as c.descrip for c in metaData.items | filter: {departmeId:selectedDepartmentId, categoryId:selectedCategoryId}">
<option value="">#String.Format(Labels.selectX, Labels.item)</option>
</select>
<div class="field-validation-error">
<span ng-show="item.$error.required">#String.Format(Messages.isRequired, Labels.item)</span>
</div>
</div>
</div>
<div class="clearfix"></div>
And this is how I use it in the form:
<data-sm:dci itemid="currentCardAct.itemId" dci="currentCardAct.dci"></data-sm:dci>
Using the logging to console I can see that card data retrieved after I need, e.g. in the console I see
Selected departmentId = 0 Selected categoryId = 0 Selected ItemId = 0
CardActController.js:221 Current Card Activity data retrieved..
smDci.js:28 Selected departmentId = 0 Selected categoryId = 0 Selected ItemId = 0
CardActController.js:221 Current Card Activity data retrieved..
I guess I can add watches in the directive's code, but is it the only option?

I solved the problem by adding a watch. I'm now trying to solve the problem with the initial selection of the item and apparently it's a known problem as referenced here http://odetocode.com/blogs/scott/archive/2013/06/19/using-ngoptions-in-angularjs.aspx about initial selection.

Related

How to apply multiple filters with pagination in Angular JS?

I am trying to apply multiple filters with pagination in Angular JS i am able to paginate the results with one filter but whenever there is multiple filters i am unable do it OR is performing among two filters instead of AND please help me to achieve this any help will be greatly appreciated. here is my code.
Here is my index.html
<html xmlns:ng="http://angularjs.org" ng-app lang="en">
<head>
<meta charset="utf-8">
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.1/css/bootstrap.no-icons.min.css" rel="stylesheet">
<link href="http://netdna.bootstrapcdn.com/font-awesome/2.0/css/font-awesome.css" rel="stylesheet">
<script src="http://code.angularjs.org/1.1.0/angular.min.js"></script>
</head>
<body>
</div>
<div ng-controller="ctrlRead">
<div class="input-append">
<input type="text" ng-model="name" ng-change="nameSearch()" class="input-large search-query" placeholder="Search Name">
<input type="text" ng-model="country" ng-change="countrySearch()" class="input-large search-query" placeholder="Search Name">
<span class="add-on"><i class="icon-search"></i></span>
</div>
<div class="pagination pull-right">
<ul>
<li ng-class="{disabled: currentPage == 0}">
<a href ng-click="prevPage()">« Prev</a>
</li>
<li ng-repeat="n in range(pagedItems.length)"
ng-class="{active: n == currentPage}"
ng-click="setPage()">
<a href ng-bind="n + 1">1</a>
</li>
<li ng-class="{disabled: currentPage == pagedItems.length - 1}">
<a href ng-click="nextPage()">Next »</a>
</li>
</ul>
</div>
</div>
</body>
</html>
And here is my script.
function ctrlRead($scope, $filter) {
// init
$scope.sortingOrder = sortingOrder;
$scope.reverse = false;
$scope.filteredItems = [];
$scope.groupedItems = [];
$scope.itemsPerPage = 5;
$scope.pagedItems = [];
$scope.currentPage = 0;
$scope.items = [
{"id":"1","name":"John","country":"usa"},
{"id":"2","name":"Peter",,"country":"London"}];
// init the filtered items
$scope.nameSearch = function () {
$scope.filteredItems = $filter('filter')($scope.items, function (item) {
if(item.name.includes($scope.name)){
return true;
}
});
$scope.countrySearch = function () {
$scope.filteredItems = $filter('filter')($scope.items, function (item) {
if(item.country.includes($scope.country)){
return true;
}
});
$scope.currentPage = 0;
// now group by pages
$scope.groupToPages();
};
// calculate page in place
$scope.groupToPages = function () {
$scope.pagedItems = [];
for (var i = 0; i < $scope.filteredItems.length; i++) {
if (i % $scope.itemsPerPage === 0) {
$scope.pagedItems[Math.floor(i / $scope.itemsPerPage)] = [ $scope.filteredItems[i] ];
} else {
$scope.pagedItems[Math.floor(i / $scope.itemsPerPage)].push($scope.filteredItems[i]);
}
}
};
$scope.range = function (start, end) {
var ret = [];
if (!end) {
end = start;
start = 0;
}
for (var i = start; i < end; i++) {
ret.push(i);
}
return ret;
};
$scope.prevPage = function () {
if ($scope.currentPage > 0) {
$scope.currentPage--;
}
};
$scope.nextPage = function () {
if ($scope.currentPage < $scope.pagedItems.length - 1) {
$scope.currentPage++;
}
};
$scope.setPage = function () {
$scope.currentPage = this.n;
};
// functions have been describe process the data for display
$scope.search();
};
ctrlRead.$inject = ['$scope', '$filter'];
Hope this will help you, I am using standard filter and 2 other drop downs through which I am doing filter in table.
HTML Code
<div>
<label>Associated Products:</label>
<div class="row">
<div class="col-md-6">
<div class="col-md-4 custom-select">
<div class="custom-select-text">{{selected}}</div>
<select class="form-control select-area c-corporate-contact-us-from-select-country country-lang-select" data-widget="custom-select"
(change)="onSelectProductLine($event)" [(ngModel)]="selected">
<option value="0">Select a product line</option>
<option *ngFor="let ProductLine of productLines" value={{ProductLine.categoryId}}>
{{ProductLine.title}}
</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="col-md-4 custom-select" *ngIf="edited">
<div class="custom-select-text">{{selectedProduct}}</div>
<select class="form-control select-area c-corporate-contact-us-from-select-country country-lang-select" data-widget="custom-select"
(change)="onSelectProduct($event)" [(ngModel)]="selectedProduct">
<option value="0">Select a product</option>
<option *ngFor="let Product of products" value={{Product.categoryId}}>
{{Product.title}}
</option>
</select>
</div>
</div>
</div>
</div>
<div class="example-header">
<mat-form-field>
<input matInput (page)="changePage($event)" (keyup)="applyFilter($event.target.value)" placeholder="Search Products based on Product Numbers or Description or Associate Products">
</mat-form-field>
</div>
JS Code
onSelectProductLine(args) {
if (args.target.value != 0)
this.edited = true;
else
this.edited = false;
this.dataservice.getProduct(args.target.value).subscribe(res => this.products = res);
this.selected = args.target.options[args.target.selectedIndex].text;
this.applyFilterTopLevelProduct(this.selected);
}
onSelectProduct(args) {
this.selectedProduct = args.target.options[args.target.selectedIndex].text;
this.applyFilterSecondLevelProduct(this.selectedProduct);
}
applyFilter(filterValue: string) {
debugger;
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
this.dataSource.filterPredicate =
(data: IFUsApi, filter: string) => {
let searchStr = (data.productNumbers + data.title + data.associatedProducts).toLowerCase();
return searchStr.indexOf(filter.toLowerCase()) != -1;
}
this.dataSource.filter = filterValue;
}
applyFilterTopLevelProduct(filterValue: string) {
debugger;
if (filterValue == "Select a product line")
filterValue = "";
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
this.dataSource.filterPredicate =
(data: IFUsApi, filter: string) => {
let searchStr = (data.toplevelProduct).toLowerCase();
return searchStr.indexOf(filter.toLowerCase()) != -1;
}
this.dataSource.filter = filterValue;
}
applyFilterSecondLevelProduct(filterValue: string) {
if (filterValue == "Select a product") {
filterValue = this.selected;
this.dataSource.filterPredicate =
(data: IFUsApi, filter: string) => {
let searchStr = (data.toplevelProduct).toLowerCase();
return searchStr.indexOf(filter.toLowerCase()) != -1;
}
this.dataSource.filter = filterValue;
}
else {
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
this.dataSource.filterPredicate =
(data: IFUsApi, filter: string) => {
let searchStr = (data.associatedProducts).toLowerCase();
return searchStr.indexOf(filter.toLowerCase()) != -1;
}
this.dataSource.filter = filterValue;
}
}

Angularjs devade tags when user put comma

I have a case in which I need to divide tags when the user put a comma separation, for the moment the user can only add tags one by one, what I want to do is allows user to enter more than one tag in the input separated by a comma:
This is what I have now :
this is what I want to do :
what I have so far :
<div class="form-group">
<label>Mes centres d'intérêt</label>
<div class="input-group" style="margin-bottom: 8px;">
<input id="tagInsert" type="text" name="newTag" ng-model="newTag" ng-model-options="{debounce: 100}" typeahead="tag for tag in getTags($viewValue)" class="form-control" typeahead-loading="loadingTags" ng-keydown="addInterestOnEvent($event)" ng-disabled="interestLimit" autocomplete="off">
<span class="input-group-btn"><span class="btn btn-primary" ng-click="addInterest()" analytics-on="click" ng-disabled="interestLimit" analytics-event="Ajout Interet" analytics-category="Profil">Ajouter</span></span>
</div>
<p class="form__field__error" ng-show="interestLimit">Vous avez atteint la limite de 10 centres d'intérêt.</p>
<ul class="tags">
<li class="tag" ng-repeat="name in user.interests track by $index">{{ name }} <i class="icon-close" ng-click="removeInterest($index)" analytics-on analytics-event="Supprimer Interet" analytics-category="Profil"></i></li>
</ul>
</div>
My controller :
$scope.getTags = function (name) {
return $http.get('/api/tags/' + name.replace('/', '')).then(function (result) {
var tags = result.data;
for (var i = tags.length; i--; ) {
var tagName = tags[i].name;
if ($scope.user.interests.indexOf(tagName) !== -1) tags.splice(i, 1);
else tags[i] = tagName;
}
return tags;
});
};
$scope.removeInterest = function (id) {
$scope.interestLimit = false;
$scope.user.interests.splice(id, 1);
}
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value;
if (value.length) {
element.value = '';
if ($scope.user.interests.indexOf(value) === -1) {
$scope.user.interests.push(value);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
};
$scope.addInterestOnEvent = function (event) {
if (event.which !== 13) return;
event.preventDefault();
$scope.addInterest();
};
$scope.remove = function () {
$scope.confirmModal = Modal.confirm.delete(function () {
User.remove(function () {
submit = true;
Auth.logout();
$location.path('/');
});
})('votre compte');
};
You should split value with comma and do for loop.
Change "addInterest" function like this:
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value.split(',');
if (value.length) {
element.value = '';
for (var i = 0; i < value.length; i++) {
if ($scope.interestLimit) break;
if ($scope.user.interests.indexOf(value[i]) === -1) {
$scope.user.interests.push(value[i]);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
}
};
As far as I understand , you want to split text into string array by comma
Try this code please
<input id='tags' type="text" />
<input type="button" value="Click" onclick="seperateText()" />
<script>
function seperateText(){
var text= document.getElementById("tags").value;
var tags = text.split(',');
console.log(text);
console.log(tags);
}
</script>

How to select quantity of individual cartItems in KnockoutJS

Hello im fairly new to knock out and im trying to have my array cartItems auto select their quantity from a drop down. Here is my code:
VIEW
<div data-bind="foreach: cartItems">
<h3 data-bind="text: fullname"></h3>
<p data-bind="text: sku"></p>
<select data-bind="quantityDropdown: number"></select>
</div>
VIEWMODEL
var number = 50;
ko.bindingHandlers.quantityDropdown = {
update: function (element) {
for (var i = 1; i < number + 1; i++) {
var selectedQty = "";
for (var x = 0; x < self.cartItems().length; x++) {
var itemqty = parseFloat(self.cartItems()[x].qty, 10);
if (i === itemqty) {
selectedQty = " selected='selected'";
}
}
// Add each option element to the select here
$(element).append("<option value='" + i + "' " + selectedQty + " class='quantity'>" + i + "</option>");
}
}
};
Now i put two items in the cart and the drop down appears. But the "selected" number is the same for both items in the cart? I know its because its not item specific. but I'm not sure how to make it item specific in Knockoutjs.
Working example:
http://jsfiddle.net/GSvnh/5085/
view :
<div data-bind="foreach: CartItems">
<h3 data-bind="text: FullName"></h3>
<p data-bind="text: Sku"></p>
<select name="qty" class="form-control" data-bind="foreach: QuantityDropdown ,value:SelectedQuantity">
<option data-bind="value: Value,text:Name"></option>
</select>
</div>
VM:
$(function () {
var MainViewModel = function () {
var self = this;
self.CartItems = ko.observableArray([]);
//For example you get below array of objects as response
var response = [{ fullname: "ABC", sku: "1234567789", qty: 12 },
{ fullname: "AAA", sku: "2323227789", qty: 20 },
{ fullname: "BBB", sku: "2311227789", qty: 33 }
];
//you map your response and for each item you create a new CartItemViewModel
self.CartItems($.map(response, function (item) {
return new CartItemViewModel(item);
}));
}
var CartItemViewModel = function (data) {
var self = this;
var number = 50;
self.FullName = ko.observable(data.fullname);
self.Sku = ko.observable(data.sku);
self.QuantityDropdown = ko.observableArray();
for (var i = 1; i < number + 1; i++) {
self.QuantityDropdown.push({ Value: i, Name: i });
}
self.SelectedQuantity = ko.observable(parseFloat(data.qty, 10));
self.SelectedQuantity.subscribe(function (newValue) {
alert("selected Qty : "+ newValue);
})
}
ko.applyBindings(new MainViewModel());
})

AngularJS clear model when changing route

I have a filter & search function in my fixed header consisting of dropdown (for filter) and input field (for search).
For the dropdown I'm using this Angularjs-dropdown-multiselect
At the moment, after submitting the request, user will be directed to result page and the model content for dropdown and input text is preserved and that's how I want it to be. The problem is, I want to reset the model (back to empty) if user go to page other than the result page.
HTML:
<div class="col-sm-3">
<div class="dropdown" ng-dropdown-multiselect="" options="cats" selected-model="catModel" checkboxes="true" translation-texts="{buttonDefaultText: 'Categories'}"></div>
</div>
<div class="col-sm-3">
<div class="dropdown" ng-dropdown-multiselect="" options="ccs" selected-model="ccModel" checkboxes="true" translation-texts="{buttonDefaultText: 'Credit Cards'}"></div>
</div>
<div class="col-sm-6">
<form data-ng-submit="findValue(catModel, ccModel, keyword)" >
<div class="input-group search-bar">
<input type="search" class="form-control" placeholder="Search for..." data-ng-model="keyword">
<span class="input-group-btn">
<button class="btn btn-search" type="button" data-ng-click="findValue(catModel, ccModel, keyword)"><img src="img/icon_search.png" alt="Search" /></button>
</span>
<input type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;"/>
</div>
</form>
</div>
JS:
.controller('mainController', ['$scope', '$http', '$location', 'dataFactory',
function ($scope, $http, $location, dataFactory){
dataFactory.getCategories().success(function (data){
$scope.cats = data;
});
dataFactory.getCcs().success(function (data){
$scope.ccs = data;
});
$scope.catModel = [];
$scope.ccModel = [];
$scope.findValue = function(catModel, ccModel, keyword) {
var searchUrl = baseUrl;
var catID = '';
if(catModel.length > 0) {
searchUrl += 'categoryID=';
angular.forEach(catModel, function(value, key) {
if(key < catModel.length - 1) {
searchUrl += value.id + ',';
catID += value.id + ',';
} else {
searchUrl += value.id;
catID += value.id;
}
})
if(ccModel.length > 0 | keyword != null) {
searchUrl += '&';
}
}
if(ccModel.length > 0) {
searchUrl += 'ccID=';
angular.forEach(ccModel, function(value, key) {
if(key < ccModel.length - 1) {
searchUrl += value.id + ',';
} else {
searchUrl += value.id;
}
})
if(keyword != null) {
searchUrl += '&';
}
}
if(keyword != null) {
searchUrl += 'search_keyword=' + keyword;
}
$http.get(searchUrl).success(function (data) {
$scope.results = data;
$scope.pageTitle = 'Promotions search result';
$location.path('/promotion');
})
}
}
I'm putting the model and function inside mainController because the header is in every view.
I'm quite new in AngularJS and programming so this code might not be proper, please let me know if there's a simpler and proper way. Any help is appreciated.
Thank you
You can subscribe to the following event $locationChangeSuccess that will be triggered on every location change.
And inside you can reset your model.
Just declare
$rootScope.$on('$locationChangeSuccess', function() {
//reset your model here
});

How to find Currently Selected value from this Custom HTML form Tag?

I have an element which is text box but its value is populated from another hidden select element.
<input type="text" id="autocompleteu_17605833" style="box-shadow: none; width: 119px;" class="mobileLookupInput ui-autocomplete-input" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
<select id="u_17605833" name="u_17605833" style="visibility: hidden">
<option value="127468">Virginia</option>
<option value="127469">Washington</option>
<option value="127470">West Virginia</option>
<option value="127471">Wisconsin</option>
<option value="127472">Wyoming</option>
</select>
var mySelObju_17605833 = document.getElementById("u_17605833");
$(function () {
var availableTagsu_17605833 = new Array();
for (var i = 0; i < mySelObju_17605833.options.length; i++) {
if (mySelObju_17605833.options[i].text != 'Other') {
availableTagsu_17605833[i] = mySelObju_17605833.options[i].text;
}
}
$("#autocompleteu_17605833").width($(mySelObju_17605833).width() + 5);
availableTagsu_17605833 = $.map(availableTagsu_17605833, function (v) {
return v === "" ? null : v;
});
$("#autocompleteu_17605833").autocomplete({
minLength: 0,
source: function (request, response) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
var a = $.grep(availableTagsu_17605833, function (item, index) {
var items = item.split(" ");
for (i = 0; i < items.length; i++) {
if (matcher.test(items[i])) return matcher.test(items[i]);
}
return matcher.test(item);
});
response(a);
},
close: function (event, ui) {
for (var i = 0, sL = mySelObju_17605833.length; i < sL; i++) {
if (mySelObju_17605833.options[i].text.toLowerCase() == $("#autocompleteu_17605833").val().toLowerCase()) {
mySelObju_17605833.selectedIndex = i;
$("#errorTDu_17605833").html("");
break;
}
mySelObju_17605833.selectedIndex = 0;
$("#errorTDu_17605833").html("Error: Invalid Input");
}
$("#autocompleteu_17605833").trigger("onchange")
}
});
});
$("#autocompleteArrowu_17605833").click(function () {
$("#autocompleteu_17605833").autocomplete("search");
$("#autocompleteu_17605833").focus();
});
$("#autocompleteu_17605833").focusout(function () {
for (var i = 0, sL = mySelObju_17605833.length; i < sL; i++) {
if (mySelObju_17605833.options[i].text.toLowerCase() == $("#autocompleteu_17605833").val().toLowerCase()) {
mySelObju_17605833.selectedIndex = i;
$("#errorTDu_17605833").html("");
break;
}
mySelObju_17605833.selectedIndex = 0;
$("#errorTDu_17605833").html("Error: Invalid Input");
}
$("#autocompleteu_17605833").trigger("onchange")
//$(this).autocomplete("close");
});
I want to find value selected in the hidden select box!
I tried to do the following
$("#autocompleteu_17605833").on("click", function (event) {
$((this.id).substring((this.id).indexOf("_") - 1)).attr("onchange", function (event) {
var selece = this.value;
alert(selece);
});
});
$("#autocompleteu_17605833").next().on("click", function (event) {
var selectedValue = document.getElementById((this.id).substring((this.id).indexOf("_") - 1)).value;
alert("Click on Arrow" + selectedValue);
});
$("#autocompleteu_17605833").on("change", function (event) {
var selectedValue = document.getElementById((this.id).substring((this.id).indexOf("_") - 1)).value;
alert("Changing the value" + selectedValue);
});
what I'm getting is older value where as I need the current assigned value.
How to achieve this??
WORKING DEMO
If am not wrong you want the selected value for this you can use select method
select:function(event,ui) {
alert("You have selected "+ui.item.label);
alert("You have selected "+ui.item.value);
}
This is a simple piece of code that will work as you required.
function result(){
document.getElementById("result").innerHTML= document.getElementById("u_17605833").value;
}
<html>
<head>
</head>
<body>
<div>
<select id="u_17605833" name="u_17605833" >
<option value="127468">Virginia</option>
<option value="127469">Washington</option>
<option value="127470">West Virginia</option>
<option value="127471">Wisconsin</option>
<option value="127472">Wyoming</option>
</select>
<input type="button" value="Show the result" onclick="result()"/>
</div>
<div id="result"></div>
</body>
</html>

Categories

Resources