Unable to bind default value to dropdown in knockoutJS - javascript

I am having two dropdown (PrimarySpeciality,PrimarySubSpeciality), based on the value in one dropdown(PrimarySpeciality) the other dropdown(PrimarySubSpeciality) value should change.
On Load, I want the 'PrimarySubSpecialities' on load to default value.
How can i do it?
my cshtml:
<div class="nmc-righttab" style="width:265px;">
#Html.DropDownListFor(m => m.User.PSpecialty, Model.PSpecialties, new { id = "ddUserDetails", style = "width:245px;height:25px;", data_bind = "event: {change: primaryChanged}" }, Model.IsReadOnly)
</div>
<div style="width:265px;">
#Html.DropDownListFor(m => m.User.PSubSpecialty,Model.PSubspecialties, new { id = "ddUserDetailsPSubSpeciality", style = "width:245px;height:25px;", data_bind = "options: pSubSpecialities,optionsText: 'Name',optionsValue: 'Id',value:PSubspecialty,enable:isPSpecialitySelected" })
</div>
My JS File:
this.PSubspecialty = ko.observable($('#ddUserDetails').val());
this.pSubSpecialities = ko.observableArray([]);
this.isPSpecialitySelected = ko.observable(false);
this.pSpecilaityChanged = function () {
var pSpecialityVal = $("#ddUserDetails").val();
if (pSpecialityVal) {
model.isPSpecialitySelected(true);
pStartIndex = 0;
pSubSpecialityUrl = '/User/GetSpec?pSpeciality=' + pSpecialityVal +'&sSpeciality=';
loadPSubSpecilaities();
}
else
{
model.isSelected(false);
}
};
On Load,I want to set initial value for 'pSubSpeciality' to be text as '<>' with value as '0'.
Even I am able to add item to Model.PSubSpecialties,but could not be able to display the added item in psubspeciality dropdown.
How can set the initial value to pSubSpecialityDropdown from Model.PSubSpecialities.

Work within your model more, and with the UI less. Instead of making a changed event on the DropDownList items, subscribe to changes on a value-bound variable. In your PrimarySpecialty DropDown,
data_bind = "value: primarySpecialty"
Then in your JS:
var self = this;
this.primarySpecialty = ko.observable();
this.isPrimarySpecialtySelected = ko.pureComputed(function () {
return !!self.primarySpecialty();
});
this.primarySubSpeciality = ko.observable();
//...
this.primarySpecialty.subscribe(function (newValue) {
if (newValue) {
loadPrimarySubSpecialities();
this.primarySubSpeciality('0'); // Set default, by value
}
});
If the PrimarySubSpeciality dropdown has an option whose Id member is '0', the item will be selected in it.

Related

How to set value kendo multiselect?

My scenario is I want to select some informations with checkbox in my grid and I can get that values like array ["3001","3004"] but when i click button kendo multiselect cannot set my values
here is onclick function:
function ongrdfleetinvoice() {
var multiselect = $("#fleetinvoice").data('kendoMultiSelect');
multiselect.value(["3001","3004"]);
}
// I also try like this same function
function ongrdfleetinvoice() {
$("#fleetinvoice").getKendoMultiSelect().value(["3001","3004"]);
}
//Here is my multiselect
#(Html.Kendo().MultiSelect().Name("fleetinvoice")
.DataTextField("CariNam")
.DataValueField("CariKod")
.Placeholder("All")
.Filter(FilterType.Contains)
.HtmlAttributes(new { style = "width: 300px;" })
.DataSource(source =>
{
source.Read(read =>
{
read.Action("FillFleet", "HeadOffice");
});
})
)
//C# Code
var resultCariler = (from m in objEntities.Cariler
where (m.CariTip == 13)
orderby m.CariNam ascending
select m).AsQueryable();
foreach (var item in resultCariler)
{
Cariler objCariler = new Cariler();
objCariler.CariKod = item.CariKod.Trim();
objCariler.CariNam = item.CariNam + - + item.CariKod.Trim();
listCari.Add(objCariler);
}
but it's not working.
Do you have any idea?
I realise something when i fill my grid and my multiselect in C# side the field names are equal but values are not equeal when i change of that and put same values.. It worked...
var resultCariler = (from m in objEntities.Cariler
where (m.CariTip == 13)
orderby m.CariNam ascending
select m).AsQueryable();
foreach (var item in resultCariler)
{
Cariler objCariler = new Cariler();
objCariler.CariKod = item.CariKod.Trim();
objCariler.CariNam = item.CariNam + - + item.CariKod.Trim(); //I changed this part with same in grid
listCari.Add(objCariler);
}
TO
var resultCariler = (from m in objEntities.Cariler
where (m.CariTip == 13)
orderby m.CariNam ascending
select m).AsQueryable();
foreach (var item in resultCariler)
{
Cariler objCariler = new Cariler();
objCariler.CariKod = item.CariKod.Trim();
objCariler.CariNam = item.CariNam;
listCari.Add(objCariler);
}

UI Hide Sensitive Data like SSN or Tax Ids and display only on button click

I am trying the below approach:
#Html.PasswordFor(m => m.TaxId )
<input type="button" id="togglePasswordField" value="Toggle Password" onclick="togglePasswordFieldClicked();" />
$(document).on("ready", function () {
var sensitiveField = document.getElementById('TaxId');
sensitiveField.type = 'password';
sensitiveField.value='#Model.TaxId';
});
function togglePasswordFieldClicked() {
var sensitiveField = document.getElementById('TaxId');
var value = sensitiveField .value;
if (sensitiveField .type == 'password') {
sensitiveField .type = 'text';
} else {
sensitiveField .type = 'password';
}
sensitiveField .value = value;
}
Requirements:
On page load the taxid value should be hidden
When users clicks a button taxid value must be shown / hidden ( toggle functionality)
3.The original value must be saved.
Issue with my approach:
Value is saved in the db but not displayed correctly in the ui ( model binding not happening )
If PasswordFor doesnt retain a value on client side , Is there any other approach I can follow to get this working ?

Preserve the hidden or visible state of initially hidden textbox on postback in mvc application

Given below is my script.My problem is I have a textbox which is hidden and is diplayed only when we select "other" from dropdownlist.On display when we enter a value after post back that value gets preserved but that textbox becomes invisible.on postback dropdown list value is however preserved and shown as "others" and only when I select someother value of dropdown and then again change it to "other" then textbox along with text gets displayed..how can I preserve that hidden or visible state of it on postback?
<script type="text/javascript">
$(document).ready(function () {
$('#SelectedCategoryId').change(function () {
if ($('#SelectedCategoryId').val() === '5') {
$('#other').show(1000);
$('#other').change(function () {
var SelectedCategory = $('#other').val().toString();
$('#hiddenId').val(SelectedCategory);
});
}
else {
$('#other').hide(1000);
var SelectedCategory = $('#SelectedCategoryId option:selected').text();
$('#hiddenId').val(SelectedCategory);
}
});
});
</script>
My View
<div id="dropdown" class="form-control dropdown">
#Html.ValidationMessageFor(m => m.SelectedCategoryId, "*")
#Html.LabelFor(m => m.Category, "Department :", new { style = "display:inline;" })
#Html.DropDownListFor(m => m.SelectedCategoryId, new SelectList(Model.Category, "Value", "Text"), "SelectCategory", new { id = "SelectedCategoryId"})
#Html.ValidationMessageFor(m => m.Other, "*")
#Html.TextBoxFor(m => m.Other, new { id = "other", #class = "other" ,style = "display: none;" })
#Html.HiddenFor(m => m.SelectedCategory, new { id = "hiddenId" })
</div>
that's becaue you only check for the value of the select on "change" event. That doesn't happen when you load the page. Do it like that:
function toggleHidden() { //that's your code in a function
if ($('#SelectedCategoryId').val() === '5') {
$('#other').show(1000);
$('#other').change(function () {
var SelectedCategory = $('#other').val().toString();
$('#hiddenId').val(SelectedCategory);
});
}
else {
$('#other').hide(1000);
var SelectedCategory = $('#SelectedCategoryId option:selected').text();
$('#hiddenId').val(SelectedCategory);
}
}
$(document).ready(function () {
toggleHidden(); //execute the toggle on load
$('#SelectedCategoryId').change(toggleHidden); //execute the toggle on change
});

Angular 1: Last checkbox doesn't stay checked after page refresh

I am saving all data into localStorage. When a checkbox is checked function is called to change items state. It works fine. However after page refresh, last checked item gets unchecked (or if it was unchecked, it gets checked) while others are working just fine. Why does that 1 last action gets ignored after page is refreshed?
Here is codepen: http://codepen.io/kunokdev/pen/vGeEoY?editors=1010
(add few items and click on "click me" for all of them and then refresh page, last action will be ignored)
The view:
<div ng-app="TaskApp" ng-controller="ToDoCtrl">
<form>
<input type="text" ng-model="toDoItem">
<input type="submit" ng-click="addToDoItem()">
</form>
<div>
<ul>
<div
ng-repeat="item in toDoItems |
orderBy: 'createdAt'
track by item.createdAt">
<b>Content:</b> {{item.content}} <br>
<b>Completed?</b> {{item.completed}}
<md-checkbox ng-model="item.completed" ng-click="toggleToDoItem(item.completed)" aria-label="todo-checkbox">
CLICK ME
</md-checkbox>
</div>
</ul>
</div>
</div>
And JS:
var ls = {};
ls.get = function(key) {
return JSON.parse(localStorage.getItem(key));
};
// sets or updates a value for a key
ls.set = function(key, val) {
localStorage.setItem(key, JSON.stringify(val));
};
// returns true if value is set, else false
ls.isSet = function(key) {
var val = ls.get(key);
return ( null === val || 'undefined' === typeof val) ? false : true;
};
// removes a set item
ls.remove = function(key) {
localStorage.removeItem(key)
};
var TaskApp = angular.module('TaskApp', [
'ngMaterial',
'taskAppControllers'
]);
var taskAppControllers = angular.module('taskAppControllers',[]);
taskAppControllers.controller('ToDoCtrl', ['$scope',
function($scope){
//
loadToDoItems = function(){
var data = ls.get("toDoData");
if (data == null) data = [];
return data;
};
//
$scope.toDoItems = loadToDoItems();
//
$scope.addToDoItem = function(){
var toDoItems = $scope.toDoItems;
var newToDoItem = {
"content" : $scope.toDoItem,
"createdAt" : Date.now(),
"completed" : false
}
toDoItems.push(newToDoItem);
ls.set("toDoData", toDoItems);
$scope.toDoItem = "";
};
//
$scope.toggleToDoItem = function(item){
console.log('test');
var toDoItems = $scope.toDoItems;
for (var i = 0; i < toDoItems.length; i++)
if (toDoItems[i].createdAt === item){
if (toDoItems[i].completed == true)
toDoItems[i].completed = false;
else
toDoItems[i].completed = true;
}
ls.set('toDoData', toDoItems);
};
//
}]);
md-checkbox is designed to toggle whatever you put in ng-model so with your code, md-checkbox was toggling the completed property and then you were changing it back again in your $scope.toggleToDoItem function. Why this worked for all the items except the last clicked I am unsure.
So I changed the ng-click to only save the items to local storage and still got the same problem which leads to me believe the problem is caused by using ng-click on an md-checkbox.
<md-checkbox ng-model="item.completed" ng-click="saveToLocalStorage()" aria-label="todo-checkbox">
CLICK ME
</md-checkbox>
$scope.saveToLocalStorage = function() {
ls.set('toDoData', $scope.toDoItems);
};
So I removed the ng-click and set up a watch on $scope.toDoItems.
<md-checkbox ng-model="item.completed" aria-label="todo-checkbox">
$scope.$watch("toDoItems", function() {
ls.set("toDoData", $scope.toDoItems);
}, true);
Codepen
-- EDIT --
Just read the documentation and feel like an idiot, you should use ng-change instead of ng-click. From the docs regarding ng-change:
Angular expression to be executed when input changes due to user interaction with the input element.
That being said, the above about not needing to toggle the completed property yourself still stands.
You are passing item.completed (in the HTML) to your toggleToDoItem(item) method. In your array loop, you then compare the item.Created field to the item.completed parameter. This is comparing a Date type to a Bool. How is that supposed to work?

Restoring default drop down value with angularjs

Although I have got this working, the way it works seems improper. I have a drop down list (DDL) that displays a list of teams. The top and default entry is "Select Team... ". Although my DDL is tied to a model, "Select Team..." shouldn't be part of it since "Select Team..." has no meaning to the domain model.
When a user clicks "Add New" the form clears and all DDLs should revert to their default values.
Here are the related controller functions:
scope.addUser = function() {
resetToNewUser();
$scope.profileVisible = true;
$scope.oneAtATime = true;
$scope.accordionStatus = { isFirstOpen: true, isFirstDisabled: false };
}
function resetToNewUser() {
$scope.selectedUser.NtId = "";
$scope.selectedUser.UserId = -1;
$scope.selectedUser.IsActive = true;
$scope.selectedUser.FirstName = "";
$scope.selectedUser.LastName = "";
$scope.selectedUser.JobTitle = "";
$scope.selectedUser.Email = "";
$scope.selectedUser.SecondaryEmail = "";
$scope.selectedUser.PhoneNumber = "";
for(var i = 0; i < $scope.roleList.length; i++) {
if($scope.roleList[i].RoleSystemName.trim() === "BLU") {
$scope.selectedUser.Role = $scope.roleList[i];
}
}
$scope.selectedUser.SupervisorId = null;
//HACK BELOW//
document.getElementById('selTeam').selectedIndex = 0; // <-- This works, but feels like a hack.
$scope.selectedUser.IsRep = false;
for(var i = 0; i < $scope.signingAuthorityList.length; i++) {
if($scope.signingAuthorityList[i].SigningAuthoritySystemName === "SME") {
$scope.selectedUser.SigningAuthority = $scope.signingAuthorityList[i];
}
}
$scope.selectedUser.IsOutOfOfficeEnabled = false;
$scope.selectedUser.OutOfOfficeStartDate = null;
$scope.selectedUser.OutOfOfficeEndDate = null;
$scope.selectedUser.OutOfOfficeAppointedRepId = null;
}
Here's how the DDL is defined in the template:
<div class="form-group">
<label for="" class="control-label col-sm-2 required">Team</label>
<div class="col-sm-10">
<select class="form-control" id="selTeam"
ng-model="selectedUser.Team"
ng-options="team as team.TeamName for team in teamList track by team.TeamId">
<option value="">Select Team...</option>
</select>
</div>
</div>
Is there a better way to do this?
You could always just remove the ability for the user to select your placeholder option, right? Something like this:
<option value="" disabled selected hidden>Select Team...</option>
You html part looks good, but I think on js side you make a lot of logic. What happens if there will be added new options on the server? Better get state of the new user from the backend, customize it with the select and other widgets and keep it before it will be submitted. On pseudo code it will be looks like
$scope.addUser = function() {
//create empty user on the scope
$scope.selectedUser = {};
//get the new user state from the backend
UserService.resetToNewUser($scope.selectedUser);
//setup view options
$scope.accordionStatus = {isFirstOpen: true, isFirstDisabled: false}
};
app.service('UserService', function(){
this.resetToNewUser = function(user){
$http({
method: 'GET',
url: '/default_user/'
}).then(function successCallback(response) {
user = response;
);
};
});

Categories