Trouble getting label from array instead of value - javascript

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.

Related

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];

Get Dynamic Input ID javascript

I have an input type check box and load from database and form like this
<input type="checkbox" name="akses[]"
id="<?php echo $menu_id;?>"
value="<?php echo $action_name;?>"> <?php echo $menu_name;?>
and my json is
{
"status": 200,
"message": "sukses",
"data": {
"fullname": "TEST",
"username": "TEST_USER",
"position": "24",
"privileges_status": "based on jabatan",
"list_menu": [{
"action_name": "menu1 ",
"parent_id": 9,
"menu_id": 15,
"menu_name": "Menu 1"
}, {
"action_name": "menu2",
"parent_id": 9,
"menu_id": 16,
"menu_name": "Menu 2"
}]
}
}
I'm already successfully parsing the id using ajax, but the problem is that I don't know how to to check when id from json is same like the id in input.
If I define manually like
<input type="checkbox" name="akses[]" id="15" value=""> Menu 1
I can check and automatically check the checkbox
Now I change my input type like this
<input type="checkbox" name="akses[]" id="menu1" value=""> Menu 1
UPDATE: The js like this after implementing suggested answer
for (var i = 0; i < res['data']['list_menu'].length; i++)
{
var action_name = res['data']['list_menu'][i]['action_name'];
var idsFromJSON = new Array();
idsFromJSON.push(action_name);
console.log(idsFromJSON);
$("[name='akses[]']").each(function() {
this.checked=idsFromJSON.indexOf(this.id)!=-1;
});
}
but didn't work. if I declare array manually like this it works
var idsFromJSON=["menu1", "menu2"];
You want something like this
I would however recommend not to have numeric IDs
var idsFromJSON=["menu15","menu16"];
$("[name='akses[]']").each(function() {
this.checked=idsFromJSON.indexOf(this.id)!=-1;
});

Angular js Properties in Selected object is not accessible in model

<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>

AngularJS Dynamically Creating Select Box - ngModel Not Registering

I am using one select box to conditionally generate a second select box. The select boxes populate correctly and everything looks okay in the Chrome Inspector on the elements.
The problem is the ng-model (ng-model="commandName" in the code example below) does not properly register the correct select value. So, if you look in the example, the {{commandName}} output at the end correctly outputs for the first select box but for the second select box nothing is output.
Is this a bug? Can anyone recommend an alternate method for approaching this problem?
Everything appears to work except commandName does not output anything in the p tag at the bottom but commandType does.
<select ng-model="commandType" class="form-control" ng-init="commandType = ''; command = ''">
<option value=""></option>
<option ng-repeat="commandGroup in commandList" value="{{$index}}">{{commandGroup.name}}</option>
</select>
<!-- Shown if something is selected in the select box above -->
<select ng-model="commandName" class="form-control" ng-if="commandType !== ''">
<option value=""></option>
<option ng-repeat="exactCommand in commandList[commandType].commands" value="{{$index}}">{{exactCommand.name}}</option>
</select>
<p>{{commandName}}</p>
AngularJS code:
$scope.initCommandList = function () {
$http({
method: 'GET',
url: $rootScope.webserver + 'admin/rterminalCommandList/',
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data) {
console.log("Command list");
console.log(data.data);
$scope.commandList = data.data;
});
};
$scope.initCommandList();
And POST response:
{
"data"
:
[{
"id": 2,
"name": "Application",
"commands": [{
"id": 3,
"name": "Delete Smartcare data",
"syntax": "su -c pm clear com.patasonic.android.smartcare",
"comment": "Deletes Smartapp data"
}]
}, {
"id": 1,
"name": "Bluetooth",
"commands": [{
"id": 2,
"name": "Bluetooth Controls. Turn off",
"syntax": "bluetooth# off",
"comment": "Turns off device bluetooth"
}, {"id": 1, "name": "Bluetooth Controls. Turn on", "syntax": "bluetooth# on", "comment": "Turn on bluetooth"}]
}], "header"
:
{
"messages"
:
[], "response_code"
:
200
}
}
I recommend you to use "select ng-options" instead of "option ng-repeat"
https://docs.angularjs.org/api/ng/directive/ngOptions
<select ng-model="myModel"
ng-options="command as command.name for command in commandList">
</select>
Here is a jsfiddle with an example:
http://jsfiddle.net/jcamelis/5y086ytr/4/
I hope it helps.

"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];

Categories