Angular js Properties in Selected object is not accessible in model - javascript

<select id="singleselect" ng-model="selectedQuestion" class="form-control select2"
ng-options="x.Title for x in tabnames">
</select>
now when i access the value if {{selectedQuestion.Title}} i am getting proper value,
when i am accessing value of {{selectedQuestion.ID}} also i am getting proper value,
what i actually need is value of {{selectedQuestion.ControlPrefix}} to be accessed in model(javascript) but it cannot be accessed neither in UI with {{selectedQuestion.ControlPrefix}} nor in model like
$scope.Newmodel = {
Title: "New Question Title",
ControlPrefix: $scope.selectedQuestion.ControlPrefix
};
basicaly i want the value inside the $scope.Newmodel.ControlPrefix variable i.e $scope.Newmodel.ControlPrefix
**tabnames array/objet is below**
{
"$id": "1",
"ID": 3,
"Title": "Text",
"ControlPrefix": "txt"
},
{
"$id": "2",
"ID": 4,
"Title": "Number",
"ControlPrefix": "num"
},

I don't See any problem with this, please check and verify -
var app = angular.module("myApp",[]);
app.controller("myCntr",function($scope){
$scope.tabnames = [
{
"$id": "1",
"ID": 3,
"Title": "Text",
"ControlPrefix": "txt"
},
{
"$id": "2",
"ID": 4,
"Title": "Number",
"ControlPrefix": "num"
},]
$scope.NewQuestionmodel = {
Title: "",
QuestionTypeID: "",
};
$scope.Dosomething = function(selectedQuestion){
$scope.NewQuestionmodel.Title = selectedQuestion.Title;
$scope.NewQuestionmodel.QuestionTypeID= selectedQuestion.ID;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCntr">
<select id="singleselect" ng-model="selectedQuestion" class="form-control select2"
ng-options="x.Title for x in tabnames" ng-change="Dosomething(selectedQuestion)">
</select>
<br>
<span>FRom UI - Selected Question Title : {{selectedQuestion.Title}} </span><br>
<span>From UI - Selected Question ID : {{selectedQuestion.ID}} </span><br>
<span>From UI - Selected Question ControlPrefix : {{selectedQuestion.ControlPrefix}} </span><br><br>
<br>
<span>Selected Question Title from Backend is {{NewQuestionmodel.Title}}</span><br>
<span>Selected Question ID from Backend is {{NewQuestionmodel.QuestionTypeID}}</span>
</div>

Related

Trouble getting label from array instead of value

So I am using an array to populate a dropdown menu and right now that part works great. I use the value to help calculate service cost and i use the label to display the option name to the user. My issue now is that my form is sending the value(which is just the price) and not the label. I may need it to do both potentially if my paypal button is my submit button? im not sure. Right now i just have the form sending to discord though.
HTML for particular selection menu
<fieldset>
<label for="rank-tourn">
Select Tournament Title
</label>
<select id="rank-tourn" name="Desired Tournament Rank" class="menus form-select" onchange="onChangeCurrent()">
<option value="0" label="" >Select</option>
</select>
</fieldset>
java for populating list
function buildOptList(select, id) {
select.innerHTML = null;
//alert("Populate list");
for (var i = id; i < Rankings.length; i++) {
if ((id == 0) && (i == Rankings.length)) {
// do nothing
} else {
var el = document.createElement("option");
el.textContent = Rankings[i].label;
el.value = Rankings[i].value;
select.appendChild(el);
}
}
}
My array
var Rankings = [{
"id": 1,
"value": 10,
"label": "Bronze Title",
}, {
"id": 2,
"value": 10,
"label": "Silver Title",
}, {
"id": 3,
"value": 15,
"label": "Gold Title",
}, {
"id": 4,
"value": 20,
"label": "Platinum Title",
}, {
"id": 5,
"value": 25,
"label": "Diamond Title",
}, {
"id": 6,
"value": 30,
"label": "Champion Title",
}, {
"id": 7,
"value": 40,
"label": "Grand Champion Title",
}, {
"id": 8,
"value": 80,
"label": "Supersonic Legend Title",
}];
I have also tried using jquery to try and copy the selection label to a hidden field but im having trouble with that too.
This was my attempted jquery:
HTML
<input type='hidden' id='hidden' value='0' label=''/>
JQUERY
$("#rank-tourn").change(function () {
$("#hidden").text($(this).text());
alert($(this).text())
})
currently this alerts on change everysingle label together. I have tried adding the :selected to rank-tourn and then it fails to alert.
https://jsfiddle.net/Popo74123/q92jh1p0/465/ this is my code if its easier.
this.text() will get the value of everything, you need to find the pseudo selector :selected to display the one that was chosen
$("#rank-tourn").change(function () {
$("#hidden").text($(this).find(':selected').text());
alert($(this).find(':selected').text())
})
Just remove this line:
el.value = Rankings[i].value;
when an option doesn't have an explicit value, it's text becomes the value.

How to trigger selection of an option using Jquery [duplicate]

I am using Angular JS and I need to set a selected option of a dropdown list control using angular JS. Forgive me if this is ridiculous but I am new with Angular JS
Here is the dropdown list control of my html
<select ng-required="item.id==8 && item.quantity > 0" name="posterVariants"
ng-show="item.id==8" ng-model="item.selectedVariant"
ng-change="calculateServicesSubTotal(item)"
ng-options="v.name for v in variants | filter:{type:2}">
</select>
After it gets populated I get
<select ng-options="v.name for v in variants | filter:{type:2}" ng-change="calculateServicesSubTotal(item)"
ng-model="item.selectedVariant" ng-show="item.id==8" name="posterVariants"
ng-required="item.id==8 && item.quantity > 0" class="ng-pristine ng-valid ng-valid-required">
<option value="?" selected="selected"></option>
<option value="0">set of 6 traits</option>
<option value="1">5 complete sets</option>
</select>
How can I set the control for value="0" to be selected?
I hope I understand your question, but the ng-model directive creates a two-way binding between the selected item in the control and the value of item.selectedVariant. This means that changing item.selectedVariant in JavaScript, or changing the value in the control, updates the other. If item.selectedVariant has a value of 0, that item should get selected.
If variants is an array of objects, item.selectedVariant must be set to one of those objects. I do not know which information you have in your scope, but here's an example:
JS:
$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.selectedOption = $scope.options[1];
HTML:
<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>
This would leave the "b" item to be selected.
I don't know if this will help anyone or not but as I was facing the same issue I thought of sharing how I got the solution.
You can use track by attribute in your ng-options.
Assume that you have:
variants:[{'id':0, name:'set of 6 traits'}, {'id':1, name:'5 complete sets'}]
You can mention your ng-options as:
ng-options="v.name for v in variants track by v.id"
Hope this helps someone in future.
If you assign value 0 to item.selectedVariant it should be selected automatically.
Check out sample on http://docs.angularjs.org/api/ng.directive:select which selects red color by default by simply assigning $scope.color='red'.
i see here already wrote good answers, but sometime to write the same in other form can be helpful
<div ng-app ng-controller="MyCtrl">
<select ng-model="referral.organization" ng-options="c for c in organizations"></select>
</div>
<script type='text/javascript'>
function MyCtrl($scope) {
$scope.organizations = ['a', 'b', 'c', 'd', 'e'];
$scope.referral = {
organization: $scope.organizations[2]
};
}
</script>
Simple way
If you have a Users as response or a Array/JSON you defined, First You need to set the selected value in controller, then you put the same model name in html. This example i wrote to explain in easiest way.
Simple example
Inside Controller:
$scope.Users = ["Suresh","Mahesh","Ramesh"];
$scope.selectedUser = $scope.Users[0];
Your HTML
<select data-ng-options="usr for usr in Users" data-ng-model="selectedUser">
</select>
complex example
Inside Controller:
$scope.JSON = {
"ResponseObject":
[{
"Name": "Suresh",
"userID": 1
},
{
"Name": "Mahesh",
"userID": 2
}]
};
$scope.selectedUser = $scope.JSON.ResponseObject[0];
Your HTML
<select data-ng-options="usr.Name for usr in JSON.ResponseObject" data-ng-model="selectedUser"></select>
<h3>You selected: {{selectedUser.Name}}</h3>
It can be usefull. Bindings dose not always work.
<select id="product" class="form-control" name="product" required
ng-model="issue.productId"
ng-change="getProductVersions()"
ng-options="p.id as p.shortName for p in products">
</select>
For example. You fill options list source model from rest-service. Selected value was known befor filling list and was set. After executing rest-request with $http list option be done. But selected option is not set. By unknown reasons AngularJS in shadow $digest executing not bind selected as it shuold be. I gotta use JQuery to set selected. It`s important! Angular in shadow add prefix to value of attr "value" for generated by ng-repeat optinos. For int it is "number:".
$scope.issue.productId = productId;
function activate() {
$http.get('/product/list')
.then(function (response) {
$scope.products = response.data;
if (productId) {
console.log("" + $("#product option").length);//for clarity
$timeout(function () {
console.log("" + $("#product option").length);//for clarity
$('#product').val('number:'+productId);
//$scope.issue.productId = productId;//not work at all
}, 200);
}
});
}
Try the following:
JS file
this.options = {
languages: [{language: 'English', lg:'en'}, {language:'German', lg:'de'}]
};
console.log(signinDetails.language);
HTML file
<div class="form-group col-sm-6">
<label>Preferred language</label>
<select class="form-control" name="right" ng-model="signinDetails.language" ng-init="signinDetails.language = options.languages[0]" ng-options="l as l.language for l in options.languages"><option></option>
</select>
</div>
This is the code what I used for the set selected value
countryList: any = [{ "value": "AF", "group": "A", "text": "Afghanistan"}, { "value": "AL", "group": "A", "text": "Albania"}, { "value": "DZ", "group": "A", "text": "Algeria"}, { "value": "AD", "group": "A", "text": "Andorra"}, { "value": "AO", "group": "A", "text": "Angola"}, { "value": "AR", "group": "A", "text": "Argentina"}, { "value": "AM", "group": "A", "text": "Armenia"}, { "value": "AW", "group": "A", "text": "Aruba"}, { "value": "AU", "group": "A", "text": "Australia"}, { "value": "AT", "group": "A", "text": "Austria"}, { "value": "AZ", "group": "A", "text": "Azerbaijan"}];
for (var j = 0; j < countryList.length; j++) {
//debugger
if (countryList[j].text == "Australia") {
console.log(countryList[j].text);
countryList[j].isSelected = 'selected';
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<label>Country</label>
<select class="custom-select col-12" id="Country" name="Country" >
<option value="0" selected>Choose...</option>
<option *ngFor="let country of countryList" value="{{country.text}}" selected="{{country.isSelected}}" > {{country.text}}</option>
</select>
try this on an angular framework
JS:
$scope.options = [
{
name: "a",
id: 1
},
{
name: "b",
id: 2
}
];
$scope.selectedOption = $scope.options[1];

How to make 'type' property of colDefn more generic in ui-grid

i am new to UI-Grid, i want to display two columns,as name and values. if i double click on cell in values column it get editable i.e its type=text. how to make cell to type checkbox, number or date. this colDefn type should get value from the data set.
code is as follows
$scope.gridOptions.data = [{
"index": 0,
"type": "Text",
"id": "name",
"title": "Name",
"value": "Some Name",
},
{
"index": 1,
"type": "date",
"id": "dob",
"title": "DOB",
"value": "1989-02-21T23:02:31+06:00",
},
{
"index": 2,
"type": "number",
"id": "age",
"title": "Age",
"value": 30,
}];
$scope.gridOptions.columnDefs = [
{ field: 'title', displayName: 'Name', enableCellEdit: false, width: '30%'},
{ field: 'value', displayName: 'Value', width: '50%'}]
I know to make columns specific to single type. But
How to make single column containing all types of fields like type="number" or "date" or "boolean(i.e is for checkbox)".
Kindly give your suggestions.
You can use a custom template, for example this one:
<div><div ng-if="!row.entity.typeCol || row.entity.typeCol === 'text' || row.entity.typeCol === 'date' || row.entity.typeCol === 'boolean'" >
<form
name="inputForm">
<input
type="INPUT_TYPE"
ng-class="'colt' + col.uid"
ui-grid-editor
ng-model="MODEL_COL_FIELD" />
</form>
</div>
<div ng-if="row.entity.typeCol === 'dropdown'">
<form
name="inputForm">
<select
ng-class="'colt' + col.uid"
ui-grid-edit-dropdown
ng-model="MODEL_COL_FIELD"
ng-options="field[editDropdownIdLabel] as field[editDropdownValueLabel] CUSTOM_FILTERS for field in editDropdownOptionsArray">
</select>
</form>
</div>
<div ng-if="row.entity.typeCol === 'file'">
<form
name="inputForm">
<input
ng-class="'colt' + col.uid"
ui-grid-edit-file-chooser
type="file"
id="files"
name="files[]"
ng-model="MODEL_COL_FIELD"/>
</form>
</div>
</div>
is a basic example of an editable cell whose type varies depending on the field typeCol.
I just copied and pasted the basic templates from ui-grid.edit and put an ng-if around each of them.
I have not tested this, but it's the only way to go, IMHO.

"selected" attribute on select option being ignored [duplicate]

I am using Angular JS and I need to set a selected option of a dropdown list control using angular JS. Forgive me if this is ridiculous but I am new with Angular JS
Here is the dropdown list control of my html
<select ng-required="item.id==8 && item.quantity > 0" name="posterVariants"
ng-show="item.id==8" ng-model="item.selectedVariant"
ng-change="calculateServicesSubTotal(item)"
ng-options="v.name for v in variants | filter:{type:2}">
</select>
After it gets populated I get
<select ng-options="v.name for v in variants | filter:{type:2}" ng-change="calculateServicesSubTotal(item)"
ng-model="item.selectedVariant" ng-show="item.id==8" name="posterVariants"
ng-required="item.id==8 && item.quantity > 0" class="ng-pristine ng-valid ng-valid-required">
<option value="?" selected="selected"></option>
<option value="0">set of 6 traits</option>
<option value="1">5 complete sets</option>
</select>
How can I set the control for value="0" to be selected?
I hope I understand your question, but the ng-model directive creates a two-way binding between the selected item in the control and the value of item.selectedVariant. This means that changing item.selectedVariant in JavaScript, or changing the value in the control, updates the other. If item.selectedVariant has a value of 0, that item should get selected.
If variants is an array of objects, item.selectedVariant must be set to one of those objects. I do not know which information you have in your scope, but here's an example:
JS:
$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.selectedOption = $scope.options[1];
HTML:
<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>
This would leave the "b" item to be selected.
I don't know if this will help anyone or not but as I was facing the same issue I thought of sharing how I got the solution.
You can use track by attribute in your ng-options.
Assume that you have:
variants:[{'id':0, name:'set of 6 traits'}, {'id':1, name:'5 complete sets'}]
You can mention your ng-options as:
ng-options="v.name for v in variants track by v.id"
Hope this helps someone in future.
If you assign value 0 to item.selectedVariant it should be selected automatically.
Check out sample on http://docs.angularjs.org/api/ng.directive:select which selects red color by default by simply assigning $scope.color='red'.
i see here already wrote good answers, but sometime to write the same in other form can be helpful
<div ng-app ng-controller="MyCtrl">
<select ng-model="referral.organization" ng-options="c for c in organizations"></select>
</div>
<script type='text/javascript'>
function MyCtrl($scope) {
$scope.organizations = ['a', 'b', 'c', 'd', 'e'];
$scope.referral = {
organization: $scope.organizations[2]
};
}
</script>
Simple way
If you have a Users as response or a Array/JSON you defined, First You need to set the selected value in controller, then you put the same model name in html. This example i wrote to explain in easiest way.
Simple example
Inside Controller:
$scope.Users = ["Suresh","Mahesh","Ramesh"];
$scope.selectedUser = $scope.Users[0];
Your HTML
<select data-ng-options="usr for usr in Users" data-ng-model="selectedUser">
</select>
complex example
Inside Controller:
$scope.JSON = {
"ResponseObject":
[{
"Name": "Suresh",
"userID": 1
},
{
"Name": "Mahesh",
"userID": 2
}]
};
$scope.selectedUser = $scope.JSON.ResponseObject[0];
Your HTML
<select data-ng-options="usr.Name for usr in JSON.ResponseObject" data-ng-model="selectedUser"></select>
<h3>You selected: {{selectedUser.Name}}</h3>
It can be usefull. Bindings dose not always work.
<select id="product" class="form-control" name="product" required
ng-model="issue.productId"
ng-change="getProductVersions()"
ng-options="p.id as p.shortName for p in products">
</select>
For example. You fill options list source model from rest-service. Selected value was known befor filling list and was set. After executing rest-request with $http list option be done. But selected option is not set. By unknown reasons AngularJS in shadow $digest executing not bind selected as it shuold be. I gotta use JQuery to set selected. It`s important! Angular in shadow add prefix to value of attr "value" for generated by ng-repeat optinos. For int it is "number:".
$scope.issue.productId = productId;
function activate() {
$http.get('/product/list')
.then(function (response) {
$scope.products = response.data;
if (productId) {
console.log("" + $("#product option").length);//for clarity
$timeout(function () {
console.log("" + $("#product option").length);//for clarity
$('#product').val('number:'+productId);
//$scope.issue.productId = productId;//not work at all
}, 200);
}
});
}
Try the following:
JS file
this.options = {
languages: [{language: 'English', lg:'en'}, {language:'German', lg:'de'}]
};
console.log(signinDetails.language);
HTML file
<div class="form-group col-sm-6">
<label>Preferred language</label>
<select class="form-control" name="right" ng-model="signinDetails.language" ng-init="signinDetails.language = options.languages[0]" ng-options="l as l.language for l in options.languages"><option></option>
</select>
</div>
This is the code what I used for the set selected value
countryList: any = [{ "value": "AF", "group": "A", "text": "Afghanistan"}, { "value": "AL", "group": "A", "text": "Albania"}, { "value": "DZ", "group": "A", "text": "Algeria"}, { "value": "AD", "group": "A", "text": "Andorra"}, { "value": "AO", "group": "A", "text": "Angola"}, { "value": "AR", "group": "A", "text": "Argentina"}, { "value": "AM", "group": "A", "text": "Armenia"}, { "value": "AW", "group": "A", "text": "Aruba"}, { "value": "AU", "group": "A", "text": "Australia"}, { "value": "AT", "group": "A", "text": "Austria"}, { "value": "AZ", "group": "A", "text": "Azerbaijan"}];
for (var j = 0; j < countryList.length; j++) {
//debugger
if (countryList[j].text == "Australia") {
console.log(countryList[j].text);
countryList[j].isSelected = 'selected';
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<label>Country</label>
<select class="custom-select col-12" id="Country" name="Country" >
<option value="0" selected>Choose...</option>
<option *ngFor="let country of countryList" value="{{country.text}}" selected="{{country.isSelected}}" > {{country.text}}</option>
</select>
try this on an angular framework
JS:
$scope.options = [
{
name: "a",
id: 1
},
{
name: "b",
id: 2
}
];
$scope.selectedOption = $scope.options[1];

knockoutjs Throws Unable to parse binding attribute

I am trying to use knockoutjs 1.2.l and with following code
$(function() {
var viewModel = {
categories: ko.observableArray([
{"Selected": false, "Text": "Rooms", "Value": "1"},
{"Selected": false, "Text": "Automobile", "Value": "2"},
{"Selected": false, "Text": "Buy & Sell", "Value": "3"},
{"Selected": false, "Text": "Tutions", "Value": "4"},
{"Selected": false, "Text": "Immigration", "Value": "5"}
]),
initialData: {
"Description": null,
"SubCategoryId": 0,
"Title": null,
"UserId": 0,
"AdTypeId": 0,
"AddressId": null,
"SubCategory": null,
"User": null,
"AdType": null,
"Address": null,
"Id": 0,
"CreatedOn": "\/Date(1307627158991)\/",
"CreatedBy": 0,
"LastUpdatedOn": "\/Date(1307627158991)\/",
"LastUpdatedBy": 0
},
chosenCategory: ko.observable()
};
ko.applyBindings(viewModel); // Makes Knockout get to work
});
Follwing is the html
<div id="createAdDiv">
<form action="/Ads/Create" method="post"> <p>
You've chosen: <b data-bind="text: chosenCategory().Text"></b>(Value: <span data-bind='text: chosenCategory().Value'></span>)
</p>
<div data-bind="visible: chosenCategory"> <!-- Appears when you select something -->
You have chosen a country with population
<span data-bind="text: chosenCategory() ? chosenCategory().Text : 'unknown'"></span>.
</div>
<fieldset>
<div class="editor-label">
<label for="SubCategoryId">Choose a Sub Category</label>
</div>
<div class="editor-field">
<select data-bind="options: categories,optionsCaption:'Choose...',optionsText: 'Text',value:chosenCategory" data-val="true" data-val-number="The field Choose a Sub Category must be a number." data-val-required="The Choose a Sub Category field is required." id="SubCategoryId" name="SubCategoryId"></select>
<span class="field-validation-valid" data-valmsg-for="SubCategoryId" data-valmsg-replace="true"></span>
</div>
</fieldset>
</form></div>
Throws the exception.
Unable to parse binding attribute. Message: TypeError: chosenCategory() is undefined;
Attribute value: text: chosenCategory().Text
But, if I change javascript to following it works
$(function() {
var viewModel = {
categories: ko.observableArray( [{"Selected":false,"Text":"Rooms","Value":"1"},{"Selected":false,"Text":"Automobile","Value":"2"},{"Selected":false,"Text":"Buy & Sell","Value":"3"},{"Selected":false,"Text":"Tutions","Value":"4"},{"Selected":false,"Text":"Immigration","Value":"5"}] )
,initialData: {"Description":null,"SubCategoryId":0,"Title":null,"UserId":0,"AdTypeId":0,"AddressId":null,"SubCategory":null,"User":null,"AdType":null,"Address":null,"Id":0,"CreatedOn":"\/Date(1307628565958)\/","CreatedBy":0,"LastUpdatedOn":"\/Date(1307628565958)\/","LastUpdatedBy":0}
};
viewModel.chosenCategory = ko.observable(viewModel.categories);
ko.applyBindings(viewModel); // Makes Knockout get to work
});
I am following an example from knockout.js website only.
You are going to want to check for null in your first paragraph tag like:
<p>
You've chosen: <b data-bind="text: chosenCategory() ? chosenCategory().Text : 'unknown'"></b>(Value: <span data-bind="text:chosenCategory() ? chosenCategory().Value : 'unknown'"></span>)
</p>
In your second snippet of code, it is working because it is reading Text and Value properties from viewModel.categories, which are just empty. If you want to set a default, then you would want to do something like viewModel.chosenCategory = ko.observable(viewModel.categories()[0]);
Another alternative is to use a template for that section and pass in chosenCategory, as they handle nulls without any extra work. Although, it would just not render that section, rather than display something like 'Unknown'

Categories