HTML.DropDownList not showing the selected value - html

Please a really need some help. I getting crazy with this one.
I'm trying to build in a page 7 Tab's with 2 DropDown's in for selecting value. The list his always the same but in each tab i have a different selected value.
Everything goes well with the first one but i can't make the second one work.
Her is my Razor code:
#Html.DropDownList("Q21_objectivos", new SelectList
(Model.Q21_ObjectivosList, "Value", "Text", Model.Q21_Objs[i - 1]),
"Seleccione um objectivo",
new
{
id = "objectivo" + i.ToString(),
#class = "form-control",
#onchange = "detectarObjectivoDuplicado( " + i + ", $(this).val() );"
})
This one is not working:
#Html.DropDownList("Q21_AvaliacaoLista",
new SelectList(Model.Q21_AvaliacaoLista, "Value", "Text", Model.Q21_Pontuacao[i - 1]),
new
{
id = "avalObjectivo" + i.ToString(),
#class = "form-control",
#onchange = "CalculaPontRes();"
})
Here is the resulting HTML:
<select class="form-control" id="objectivo1" name="Q21_objectivos" onchange="detectarObjectivoDuplicado( 1, $(this).val() );"><option value="">Seleccione um objectivo</option>
<option selected="selected" value="1">Preencher as tarefas em DotProject até ao dia 1 do mês seguinte</option>
<option value="2">Desenvolver aplicação SIADAP3</option>
<option value="3">Resolver 70% dos tickets atribuidos</option>
<option value="4">Desenvolver 2 aplicações locais em VB.net</option>
<option value="5">Desenvolver 2 aplicações locais em COBOL</option>
</select>
The resulting HTML of the not selecting dropdownlist:
<select class="form-control" id="avalObjectivo1" name="Q21_AvaliacaoLista" onchange="CalculaPontRes();"><option value="5">Superado (Pontuação 5)</option>
<option value="3">Atingido (Pontuação 3)</option>
<option value="1">Não Atingido (Pontuação 1)</option>
<option value="0">Avalie o Objectivo</option>
</select>
What can I say more... The model is loaded with the list as it's possible to see in the resulting HTML.

If you change the property name "Q21_AvaliacaoLista" to something else, the selectedvalue will work.
The property name (Q21_AvaliacaoLista) and the list of items (Model.Q21_AvaliacaoLista) cannot have the same name.
Maybe it is because of data biding of MVC...

I just made it work by changing "Q21_AvaliacaoLista" to "Q21_Avaliacao" in the DropDownList that wasn't working.
Somehow the name was making probably a conflict. I don't understand why but this way it's working.

Related

Can't figure out a way to add two values from a select element in react

Scenario: I have a react component that allows users to select through different shipping rates. Once a user selects one I want the onChange to get the ID and the amount and I can only figure out how to get just the ID. The select element iterates through an array of rates that is structured like this:
rates = [ {id: 'r8f8hd8', amount: 45}, ...]
Here is the select element:
<select onChange={(e) => console.log(e.target.value)} className='w-8/12 h-14 rounded p-2'>
<option disabled selected hidden>
Pick a shipping rate
</option>
{rates.map((rate, index) => (
<option value={{ id: rate.rateId, amount: rate.amount }} key={index}>
{rate.service} {''}(${rate.amount})
</option>
))}
</select>
I tried setting the option value to an object with the rateId and amount but it just gives me a blank [Object object]
This should fix the issue. A word of advice I wouldn't set the key to just the index. Instead you should use the id that you assigned to the object.
The issue was you we're storing an object as the value. This lead to an issue because value automatically stores a string so your object is converted into a string hence [Object Object]. Mapping already sets its own pre defined object {value:someVal,key:someID}.
Taking your current case into account I believe this is a cleaner way to achieve what you wanted. I've added working code below. Also the extra item in rates was just for testing.
Feel free to comment any questions you have and i'll do my best to answer them.
let rates = [ {id: 'r8f8hd8', amount: 45},{id: 'r8f8hd', amount: 450}]
return (
<select onChange={(e) => console.log(e.target.value)} className='w-8/12 h-14 rounded p-2'>
<option disabled selected hidden>
Pick a shipping rate
</option>
{rates.map((rate) => (
<option value={rate.amount } key={rate.id}>
{rate.service} {''}(${rate.amount})
</option>
))}
</select>
)
Just incase your just dead set on storing multiple values here's a solution to that as well but I would go as far as saying this is just bad code but it does what you wanted. Since map has its own object as I mentioned we can mutate it and give it more characteristics hence id and trueVal that I added. We can use the index and store that as our value and instead of accessing our data through e.target.value we can instead utilize the e.target.options and simply cross reference the index value we stored to make sure we are always accessing the correct position in the array. However please take note of the +1 this is to take the first position into account which is held by the, "Pick a shipping rate".
let rates = [ {id: 'r8f8hd8', amount: 45},{id: 'r8f8hd', amount: 450}]
return (
<select onChange={(e) => console.log(e.target.options[e.target.value])} className='w-8/12 h-14 rounded p-2'>
<option disabled selected hidden>
Pick a shipping rate
</option>
{rates.map((rate, index) => (
<option value={index+1} trueVal={rate.amount} id={rate.id} key={index}>
{rate.service} {''}(${rate.amount})
</option>
))}
</select>
)
}
In html value prop is a string, so value={{ id: rate.rateId, amount: rate.amount }} is converted to string, that's why you are getting [Object object] .
Solution : change your component like this :
.....
const [option, setOption] = React.useState({});
const handlechange = (e)=>{
for (let i = 0; i < rates.length; i++) {
if (e.target.value === rates[i].id) {
setOption({ id: rates[i].id, amount: rates[i].amount });
}
}
}
return (
<select onChange={handlechange} className="w-8/12 h-14 rounded p-2">
<option disabled selected hidden>
Pick a shipping rate
</option>
{rates.map((rate, index) => (
<option value={rate.id} key={index}>
{rate.service} {""}(${rate.amount})
</option>
))}
</select>
);
Now your id and amount of selected option will be stored in option state
this is a demo in codesandbox

How do I change the value in <p id=[value] in html

I've asked a version of this question before and am very grateful for the help I've got but I'm still stuck so I thought it better to ask a refined question which now gets to the nub.
I've got the code below. The idea is that the select command should choose a value (initially XA, but could be XB, XC, XD) which will then be substituted for XA in the opening <span line and cause the appropriate document.getElementById line at the end to write.
But it doesn't work as it stands. Can anyone tell me how to correct it.
<span id="XA">Change</span>
<P>
<select class="selector" onchange="document.querySelector('p').id=this.value; console.log(document.querySelector('p').id)">
<option value="XA" selected>XA</option>
<option value="XB">XB</option>
<option value="XC">XC</option>
<option value="XD">XD</option>
</select>
<p id="XA"></p>
<p id="XB"></p>
<p id="XC"></p>
<p id="XD"></p>
<script>
document.getElementById("XA").innerHTML = "Option is XA";
document.getElementById("XB").innerHTML = "Option is XB";
document.getElementById("XC").innerHTML = "Option is XC";
document.getElementById("XD").innerHTML = "Option is XD";
</script>
First I would fix your html and make sure your ids are unique then you can do the following
const span = document.getElementById('text');
document.querySelector('.selector')
.addEventListener('change', event => {
const thisValue = event.currentTarget.value; // get current value
const text = `Option is ${thisValue}`;
span.innerText = text; // change span text
document.getElementById(thisValue).innerText = text; // change p value
});
<span id="text">Change</span>
<select class="selector">
<option value="XA" selected>XA</option>
<option value="XB">XB</option>
<option value="XC">XC</option>
<option value="XD">XD</option>
</select>
<p id="XA"></p>
<p id="XB"></p>
<p id="XC"></p>
<p id="XD"></p>

Trying to get html Dropbox (2 step) working with vba code

Trying to get a dropbox working from vba code but it seems to have a two-step process before the drop box opens. (Like authentication, the displays a box about the dropbox so you can select and it inserts it into the box. But it is all in the one dropbox, but I think the authentication side is hidden. I can get a basic Dropbox to work with indexes but this one has me stumped. I do not fully understand as fairly new to VBA > HTML side of things.
But my understanding is "SchProgramID" is the authentication or filter code then once it has received that the "TrainerId" will open to give you selected names of which is filtered into a box as you type or you can be selected with a mouse from the list.
I cannot even get focus on either.
Can someone please help me?
The html code from the site is as follows:
<div class="form-group">
<label class="control-label col-md-2" for="TrainerId">Trainor</label>
<div class="col-md-8">
<select class="form-control chosen-select" data-live-search="true" data-val="true" data-val-number="The field Trainor must be a number." data-val-required="The Trainor field is required." id="TrainerId" name="TrainerId"><option value="">Select Trainor</option>
<option value="176">Undrico Divina Corpuz Jr.</option>
<option value="204">Domingo Bagadiong Go Jr.</option>
<option value="1200">Marnilo Sayson Sugano </option>
<option value="1238">Dexter Gaoiran Tomas </option>
Code I have been playing with
'Dim fromSelect, fromSelect1 As HTMLSelectElement
'Dim evt, evt1 As Object
'Set evt = htmlDoc.createEvent("HTMLEvents")
'Set evt1 = htmlDoc.createEvent("HTMLEvents")
'evt.initEvent "change", True, False
'evt1.initEvent "change", True, False
'Set fromSelect = htmlDoc.getElementById("SchProgramId")
'OptionValue = "14526"
'If optionIndex >= 0 Then
' fromSelect.selectedIndex = OptionValue
' fromSelect.dispatchEvent evt
'Set fromSelect1 = htmlDoc.getElementById("TrainerId")
'OptionValue = "9570"
If optionIndex >= 0 Then
' fromSelect.selectedIndex = OptionValue
' fromSelect.dispatchEvent evt1
end if
I am not clear on the role of SchProgramId at present.
For showing the dropdown you should be able to use:
ie.document.getElementById("TrainerId").Click
For selecting elements in the dropdown you should be able to target the value attribute by its value e.g. 1421 for the first trainer (or by index)
ie.document.querySelector("#TrainerId option[value='1421']").Selected = True
Example using index:
ie.document.querySelector("#TrainerId").selectedIndex = 2

Display label displayed in options as the title of select

How to show option.Brand.Name as the title of the select field without using java script and changing the ng-model?
<select ng-model="detail.BrandId" title="" class="form-control" disabled>
<option ng-repeat="option in mainCtrl.products" ng-selected="option.Id === detail.ProductId" ng-value="option.BrandId">{{option.Brand.Name}}</option>
</select>
AngularJS and select-options
Try using ng-options AngularJS ngOptions directive within select element itself. Then you don't need to add each option element yourself using ng-repeat.
Clarification
The title-attribute belongs to the select-element and will show if you hover over the select. You would like the title to reveal the current selected option? Did I understand you correctly?
How to show option.Brand.Name as the title of the select field
Curious, where this detail.ProductId comes from? Is the brand preselected by product-id (see your code)?
ng-selected="option.Id === detail.ProductId"
Solution space
Your requirements/restrictions are:
without using JavaScript (maybe because you can't change the sources)
without changing the ng-model (because you need there only the BrandId for some database-reasons)
So since the title of the select-element has no access to the options inside, the only way to set it is depending on the current selection, i.e. your detail.BrandId. So the title can only set dynamically (depending on the current selection) by using standard-angularJS means, as:
{{ expression }} expressions
{{ expression | filter }} array-filter
Expected behavior
The only scope-variable changed by selecting is specified within select's ng-model as detail.BrandId. This will be set when user selects an option to its property BrandId. When user selects between options they will be visible with ther BrandName as label. After selection this BrandName (label of the option) should be shown as title of the entire select element.
So we need to get from detail.BrandId (selected ng-model) to related options BrandName (as this should show as title).
Possible Solution
Only way is to use standard angular expressions/filters/array-indexing to get the whole option by the selected detail.BrandId (ng-model)
Then we can lookup the option.BrandName by this equation after selected detail.BrandId === option.BrandId
var app = angular.module('app', []);
app.controller('mainCtrl', function($scope){
$scope.products = [
{Id: 0, name: 'Watson', brandId: 1, brandName:"IBM"},
{Id: 1, name: 'DB2', brandId: 1, brandName:"IBM"},
{Id: 2, name: 'Windows', brandId: 2, brandName: "Microsoft"},
{Id: 3, name: 'Office', brandId: 2, brandName: "Microsoft"}
];
$scope.detail = { ProductId: 3, BrandId: null };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<!DOCTYPE html>
<html>
<body data-ng-app="app" data-ng-controller="mainCtrl">
<table border="1">
<tr>
<th>Product Id</th><th>Product Name</th><th>Choose Brand</th><th>Brand Id</th>
</tr>
<tr>
<td>{{detail.ProductId}}</td>
<td>{{ (products | filter: {Id: detail.ProductId})[0].name }}</td>
<td>
<select class="form-control"
ng-model="detail.BrandId"
ng-init="detail.BrandId = (products | filter: {Id: detail.ProductId})[0].brandId"
ng-options="o.brandId as ('['+ o.Id +'] '+ o.name +' : '+ o.brandName +' ('+ o.brandId +')') for o in products"
title="{{ (products | filter: {brandId: detail.BrandId})[0].brandName}}"
>
<!-- default option when not preset by detail.ProductId-->
<option value="">-- please choose brand --</option>
</select>
</td>
<td>{{detail.BrandId}}</td>
</tr>
</table>
<hr/>
<p>Product is predefined. So the brand is pre-selected by product. BUT: after brand is selected, the product-details do NOT change!</p>
Selected <strong>detail</strong>:
<pre ng-model="selected">{{detail | json}}</pre>
</body>
</html>
See also
For using ng-options, see also plunkr example.
You can register the selected option object in the ng-repeat parent scope by using as alias-expression provided by ng-repeat.
In your case you just need to do something like that:
<select ng-model="detail.BrandId"
title="{{options | selectedProductFilter : detail.ProductId}}"
class="form-control"
disabled>
<option ng-repeat="option in mainCtrl.products as options"
ng-selected="option.Id === detail.ProductId"
ng-value="option.BrandId">
{{option.Brand.Name}}
</option>
</select>
The options object will be available in your controller closure and you can display the title by using a custom filter.
angular.module("app").filter('selectedProductFilter',
function () {
return function (input, id) {
if (!input) return "";
let occurence = input.filter(function (x) {
return x.Id == id;
});
return occurence.length > 0 ? occurence[0].Brand.Name: "";
}
}
);
you need to do ng-change event in your select and call function in it that change the value of label text to the select value name. something like below
In Html
ng-change="changedValue(detail.BrandId)"
In JS
$scope.changedValue = function(item) {
//change label name here
}
fill ng-model by "option" not "option.BrandId"
then you can set title like this :
mainCtrl.products['ng-model-name'].Brand.Name
Here's how you could achive this:
(function () {
"use strict";
const app = angular.module("app", []);
app.controller("app.AppCtrl", $scope => {
$scope.selectedOption = null;
$scope.optionList = [{_id: 1, label: 'Option 1'}, {_id: 2, label: 'Option 2'}];
});
})();
body {
margin: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="app.AppCtrl">
<select title="{{selectedOption.label}}" class="form-control" ng-model="selectedOption">
<option ng-repeat="option in optionList" ng-value="option"> {{option.label}}</option>
</select>
</div>
Try using ng-init,
add ng-init to your select tag and put your object index value you want to be selected by default.
e.g.
Your code
<select ng-model="detail.BrandId" title="" class="form-control" disabled>
<option ng-repeat="option in mainCtrl.products" ng-selected="option.Id === detail.ProductId" ng-value="option.BrandId">{{option.Brand.Name}}</option>
</select>
adding following code (Suppose I want index 0 by index):
ng-init="detail.BrandId = option[0].Brand.Name"
It will look like this :
<select ng-model="detail.BrandId" ng-init="detail.BrandId = option[0].Brand.Name" title="" class="form-control" disabled>
<option ng-repeat="option in mainCtrl.products" ng-selected="option.Id === detail.ProductId" ng-value="option.BrandId">{{option.Brand.Name}}</option>
</select>
or Check these thread's
how to use ng-option to set default value of select element
How to set default value in ng-options

How to change select tags value when element is deleted from array?

I have select tag which takes values from array like this
<select class="groupForArchive" ng-model="selected.country">
<option ng-selected= "{{country == selected.country}}" ng-repeat="country in countrynList" value={{country}}> {{ country.name }} </option>
</select>
when I am deleting element from array(countryList) I am setting new value to this tag like this $scope.selected.country = newValue, but in select box I am getting free space like in this pictures.
before delete country from list
after delete country from list
and when I am taking select tag's ng-model I am getting correct object but I can not see it in my select box and I don't know which item is selected.
P.S newValue is array's another item(item from countrynList)
How can I fix it ?
Update AngularJS library to latest version and make changes, presented below:
angular.module('app', []).controller('ctrl', function($scope){
$scope.countrynList = [
{name:'USA'}, {name:'Spain'}, {name:'France'}, {name:'Germany'}
]
$scope.selected = {country: $scope.countrynList[0]};
$scope.Delete = function(){
var index = $scope.countrynList.indexOf($scope.selected.country);
$scope.countrynList.splice(index, 1);
$scope.selected.country = $scope.countrynList[0];
}
})
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<div ng-app='app' ng-controller='ctrl'>
<select class="groupForArchive" ng-model="selected.country">
<option ng-repeat="country in countrynList" ng-value='country'>
{{country.name}}
</option>
</select>
{{selected.country}}
<br>
<input type='button' ng-click='Delete()' value='Delete First'/>
</div>