dropdown selected value not setting and displaying blank text in angular js - javascript

I am working on C#/MVC application with angularJS. I need to display dropdown on popup, If record already have value then by default that value should be selected otherwise default option choose an option.
I am able to bind dropdown and If I debug I am getting correct ng-model value but its displaying blank.
Here is controller code on pop up open click
$scope.ShowAdPopup = function (adId) {
$scope.Popup.CategoryId = 0;
$scope.Popup.InterestId = 0;
$scope.Popup.SourceId = 0;
var filteredData = $filter('filter')($scope.gridAdData, { id: adId }, true);
if (filteredData.length > 0) {
$scope.Popup.Id = filteredData[0].id;
$scope.Popup.AdId = filteredData[0].adId;
$scope.Popup.AdName = filteredData[0].adName;
$scope.Popup.Category = filteredData[0].category;
$scope.Popup.Interest = filteredData[0].interest;
$scope.Popup.Source = filteredData[0].source;
$scope.Popup.AdUrl = filteredData[0].adUrl;
$scope.Popup.CategoryId = filteredData[0].categoryId;
$scope.Popup.InterestId = filteredData[0].interestId;
$scope.Popup.SourceId = filteredData[0].sourceId;
}
$("#divAddGroup").modal({ show: true, backdrop: 'static', keyboard: false });
}
And html is as below
<div class="form-group">
<label class="col-sm-3 control-label">Category</label>
<!--<div class="col-sm-9">
<input type="text" name="category" class="form-control" ng-model="Popup.Category" />
</div>-->
<div class="col-sm-9">
<select class="form-control" name="categoryDrp" ng-model="Popup.CategoryId">
<option value="">-- choose an option --</option>
<option ng-repeat="item in CategoryData" value="{{item.id}}">{{item.categoryName}}</option>
</select>
</div>
Now If I debug and I can see CategoryId setting correct id . e.g. 7 or 8 or 9 which CategoryData have already but its display 'blank' as first option if Id is available
If CategoryId is null then it display '-- choose an option --' which is correct

Try ng-selected="item.id == Popup.CategoryId" as :
<select class="form-control" name="categoryDrp" ng-model="Popup.CategoryId">
<option value="">-- choose an option --</option>
<option ng-repeat="item in CategoryData" value="{{item.id}}"
ng-selected="item.id == Popup.CategoryId">{{item.categoryName}}</option>
</select>

Related

Drop down when select the option from ajax another input field appear

Hi i needed some help where if i select a drop down and select from ajax option and a hidden input field appear how can i do it ?
<div class="form-row">
<div class="col">
<label for="select-price-mode" class="col-form-label">Price Mode</label>
<select class="select-price-mode custom-select-sm col-10" id="select-price-mode" required>
<option selected disabled value="">Select ....</option>
</select>
</div>
<div class="col" hidden>
<label for="select-payment-frequency" class="col-form-label">Payment Frequency</label>
<select class="select-payment-frequency custom-select-sm col-10" id="select-payment-frequency" required>
<option selected disabled value="">Select ....</option>
</select>
</div>
This is my ajax
// Here the calling Ajax for the drop down menu below
$.ajax({
// The url that you're going to post
/*
This is the url that you're going to put to call the
backend api,
in this case, it's
https://ecoexchange.dscloud.me:8080/api/get (production env)
*/
url:"https://ecoexchange.dscloud.me:8090/api/get",
// The HTTP method that you're planning to use
// i.e. GET, POST, PUT, DELETE
// In this case it's a get method, so we'll use GET
method:"GET",
// In this case, we are going to use headers as
headers:{
// The query you're planning to call
// i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
query:"PriceModeGet()",
// Gets the apikey from the sessionStorage
apikey:sessionStorage.getItem("apikey")
},
success:function(data,textStatus,xhr) {
console.log(data);
for (let option of data) {
$('#select-price-mode').append($('<option>', {
value: option.PriceMode,
text: option.PriceMode
}));
}
},
error:function(xhr,textStatus,err) {
console.log(err);
}
});
and this is my ajax response
[
{
"PriceMode": "Price By Recyclables"
},
{
"PriceMode": "Service Charger"
}
]
Where say if i select Price By Recyclables the hidden drop down list appear how can i do it ?
You can use the onchange event to trigger a check and if the user selected the value you want, then display the selectbox. You'd have to add an id to the div with the hidden prop (divToDisplay).
$("#select-price-mode").change(function() {
if(this.value === "Price By Recyclables") {
$('#divToDisplay').removeAttr('hidden');
}
});
Just invoke a function when an option is selected in first select
const checkPriceMode = () => {
let value = $('.select-price-mode').val();
$('.payment-frequency').fadeOut();
if(value === 'Price By Recyclables') $('.payment-frequency').fadeIn();
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-row">
<div class="col">
<label for="select-price-mode" class="col-form-label">Price Mode</label>
<select onchange="checkPriceMode()" class="select-price-mode custom-select-sm col-10" id="select-price-mode" required>
<option selected disabled value="">Select.....</option>
<option value="Price By Recyclables">Price By Recyclables</option>
<option value="Service Charger">Service Charger</option>
</select>
</div>
<div class="col payment-frequency" hidden>
<label for="select-payment-frequency" class="col-form-label">Payment Frequency</label>
<select class="select-payment-frequency custom-select-sm col-10" id="select-payment-frequency" required>
<option selected disabled value="">Select ....</option>
</select>
</div>

set the value of select option dynamically

This is my code. I am trying to set the value of select tag from database. but it's not working as expected. My requiremnet is value='Auto' then 0th index should be selected else 1sst index should be selected. But its not happening that way. can some one help me?
<div class="form-group">
<label class="medium mb-1" for=""> Select Mode of Update </label>
<select class="form-control" name="avupdatemode" value="<%= data.updatemode %>" >
<option value="Auto" >Auto Update</option>
<option value="Manual">Manual</option>
</select>
</div>
<script>
var sel= document.getElementById('avupdatemode');
if(document.getElementById('avupdatemode').value =='Auto'){
sel.options.selectedIndex = 0;}
else{
sel.options.selectedIndex = 1;
}
</script>
First there is no id attribute on your select.
Second .value will take the value from the selected option and not the value attribute from the select.
So i've added data-value="sAuto" to the select and then done document.getElementById('avupdatemode').dataset.value == 'Auto'
DEMO
var sel = document.getElementById('avupdatemode');
if (document.getElementById('avupdatemode').dataset.value == 'Auto') {
sel.options.selectedIndex = 0;
} else {
sel.options.selectedIndex = 1;
}
<div class="form-group">
<label class="medium mb-1" for=""> Select Mode of Update </label>
<select class="form-control" id="avupdatemode" name="avupdatemode" data-value="sAuto">
<option value="Auto">Auto Update</option>
<option value="Manual">Manual</option>
</select>
</div>
I am getting my backend data in an array to my ejs page.
So I tried this and it worked:
var sos = <%- JSON.stringify(sos) %>;
I iterated the array and based on the value i set my index for the select option.

Remove selected option from drop down in Angular

I have a button which adds more select drop downs when clicked. So I would like to remove the already selected options in these select boxes for preventing duplication.
The following code is used for the select drop down:
<select class="select form-control"
formControlName="environment_id" (change)="onEnvChange($event.target.value)">
<option selected="selected" disabled value="">Select Environment
</option>
<ng-container *ngFor="let environment of environments">
<option *ngIf="!selectedEnvironments.includes(environment.environment_id)"
[value]="environment.environment_id">
{{environment.environment_id}}</option>
</ng-container>
</select>
and in the component I ave the following function for change
public onEnvChange(selectedEnvironment)
{
this.selectedEnvironments.push(selectedEnvironment);
}
Now when I select an option, that option itself gets removed from the dropdown. For example if I have options like option1,option2,option3 etc, when I select option1, option1 is getting removed from the dropdown. How to fix this and remove the option only for the next select dropdown ?
You can try create two objects of environments and listen selection with valueChanges from formControl. After you get the selected environmentid and filter the other object without this id
Example
ngOnInit(){
this.createForm();
this.getEnvironments();
this.environmentChanges()
}
createForm(){
this.form = this.fb.group({
'environment_id_1': [''],
'environment_id_2' : ['']
})}
getEnvironments(){
const environments = [
{ 'environment_id': 1, 'environment': 'A' },
{ 'environment_id': 2, 'environment': 'B' },
{ 'environment_id': 3, 'environment': 'C' },
{ 'environment_id': 4, 'environment': 'D' }];
this.environments1 = environments;
this.environments2 = environments;}
environmentChanges(){
this.form.controls['environment_id_1'].valueChanges
.subscribe((environment_id)=>{
this.environments2 = this.environments1.filter((env)=> env.environment_id != environment_id)
})}
<form [formGroup]="form">
<div class="row">
<select class="select form-control" formControlName="environment_id_1">
<option value="">Select Environment 1 </option>
<option *ngFor="let environment of environments1" [value]="environment.environment_id"> {{environment.environment}} </option>
</select>
</div>
<div class="row" style="padding-top: 10px;">
<select class="select form-control" formControlName="environment_id_2">
<option value="">Select Environment 2 </option>
<option *ngFor="let environment of environments2" [value]="environment.environment_id"> {{environment.environment}} </option>
</select>
</div>
enter image description here

Unable to add options to the select dynamically from json

i have this select, with id category and product. If a choose one option in the select category, the other should list all products in that category.
var json = JSON.parse(xhr.responseText);
console.log('value: '+e.value);
for(var x in json) {
console.log(x+' -> id: '+json[x]['id']);
var all = document.getElementById(target).querySelector("#all");
document.getElementById(target).innerHTML = '';
document.getElementById(target).appendChild(all);
var data = json[x];
if(e.value == '*') {
console.log('add ('+data['id']+', '+data['nome']+')');
var child = document.createElement("option");
child.setAttribute("value", data['id']);
child.innerText = data['nome'];
document.getElementById(target).appendChild(child);
} else {
if(data['categoria'].id == e.value) {
console.log('add ('+data['id']+', '+data['nome']+')');
var child = document.createElement("option");
child.setAttribute("value", data['id']);
child.innerText = data['nome'];
document.getElementById(target).appendChild(child);
}
}
}
<div class="row">
<div class="col-sm">
Category:
<select class="form-control" id="category" data-target="product" th:attr="data-url=#{/produto/listBy.json}" onchange="fill_produtos(this);">
<option value="*">All</option>
<option th:each="option : ${categories}" th:value="${option.id}">
<span th:each="t : ${option.nome}" th:if="${#strings.equals(#strings.substringBefore(t.idioma,','), #strings.replace(#locale,'_','-'))}" th:href="#{/categoria/__${t.conteudo}__}" th:text="${t.conteudo}"></span>
</option>
</select>
</div>
<div class="col-sm">
Produto:
<select class="form-control" id="product">
<option id="all" value="*">All</option>
<option th:each="option : ${produtos}" th:value="${option.id}" th:text="${option.nome}"></option>
</select>
</div>
<div class="col-sm">
Date Range: <input type="date" class="form-control"> a <input type="date" class="form-control">
</div>
</div>
Right now, this is not happening as expected. I have this 3 categories (named one, two and three), each one with 1 product (prod1, prod2 and prod3). I select categories one or two, no products are listed on the other select; if I select category three or all, only the product three are listed on the other select.
Except that the debug code (the console.log) added to the function seems to follow the right path when I click each option on category: if I click one, only the message inside the if(data['categoria'].id == e.value) is shown; same for two and three. If click all, all messages are shown, as expected, due the instruction telling to do so after if(e.value == '*').
Anyone can see what I am doing wrong here? I know I am missing something, but I can't see what is.

Dependent drop-down list from map in Thymeleaf

I want to create a drop-down list with countries and the second drop-down list with cities, which depends on selected value in the first list. And the list of cities should be changed dynamically.
In the view (Thymeleaf) I have a Map<CountryModel, Set<RegionModel>> from controller. CountryModel's name should be shows in the second drop-down list, and Set should be shows in the second(dependent) drop-down list.
Here I create first drop-down list:
<tr>
<td th:text="#{country}"/>
<td>
<div class="form-group">
<select th:field="*{transferRequestModel.country}" class="form-control" id="country">
<option th:each="country : ${transferModel.countries}"
th:value="${country}"
th:text="${country.key.countryName}">Wireframe
</option>
</select>
</div>
</td>
</tr>
So how to create second drop-down list which depends on selected country in the first list?
So I have solved my problem with AJAX request and jQuery append.
Change Map<CountryModel, Set<RegionModel>> to Map<String, Set<String>>
AJAX request
function sendAjaxRequest() {
var country = $("#country").val();
$.get( "/regions?country=" + country, function( data ) {
$("#region").empty();
data.forEach(function(item, i) {
var option = "<option value = " + item + ">" + item + "</option>";
$("#region").append(option);
});
});
};
Use sendAjaxRequest() when i change first drop-down list.
$(document).ready(function() {
$("#country").change(function() {
sendAjaxRequest();
});
});
Drop-down list at the Thymeleaf template
First drop-down list
<td th:text="#{country}"/>
<td>
<div class="form-group">
<select th:field="*{model.country}" class="form-control" id="country">
<option th:each="country : ${model.countries}"
th:value="${country}"
th:text="${country}">Wireframe
</option>
</select>
</div>
</td>
Second drop-down list
<td>
<div class="form-group">
<select th:field="*{requestModel.region}" class="form-control" id="region">
</select>
</div>
</td>
Controller
#RequestMapping(value = "/regions")
#ResponseBody
public Set getRegions(#RequestParam String country) {
Map<String, Set<String>> regions = regionsService.getRegions();
return regions.get(country);
}
In our project we did it like that:
<div class="form-group">
<label class="col-sm-4 control-label"
th:text="#{person.edit.policy.tfoms}"></label>
<div class="col-sm-8">
<select class="form-control" th:field="*{tfoms}"
onchange="loadInsuranceCompanies()">
<option th:each="t : ${tfomses}"
th:value="${t.uidtfoms}"
th:text="${t.shortName}"
th:selected="${personBean.tfoms != null
and personBean.tfoms.equals(t)}">
</option>
</select>
</div>
</div>
<div th:class="${#fields.hasErrors('insuranceCompany')}
? 'form-group has-error' : 'form-group'">
<label class="col-sm-4 control-label"
th:text="#{person.edit.policy.ic}">
</label>
<div class="col-sm-8" id="insuranceCompaniesContent">
<select class="form-control" id="insuranceCompany"
name="insuranceCompany"
th:fragment="insuranceCompany">
<option th:each="i : ${insuranceCompanies}"
th:value="${i.uidinsurancecompany}"
th:text="${i.shortName}"
th:selected="${personBean.insuranceCompany != null
and personBean.insuranceCompany.equals(i)}">
</option>
</select>
<div th:if="${#fields.hasErrors('insuranceCompany')}"
th:each="err : ${#fields.errors('insuranceCompany')}">
<span class="text-danger" th:text="${err}"></span><br/>
</div>
</div>
</div>
Insurance companies loading function loadInsuranceCompanies():
function loadInsuranceCompanies() {
var url = /*[[#{/PersonEdit/insuranceCompanies}]]*/ "/PersonEdit/insuranceCompanies";
if ($('#tfoms').val() !== '') {
url = url + '/' + $('#tfoms').val();
}
$("#insuranceCompaniesContent").load(url);
}
And finally code in controller:
#RequestMapping(value = "/PersonEdit/insuranceCompanies/{tfoms}", method = RequestMethod.GET)
public String getInsuranceCompaniesByTfoms(#PathVariable("tfoms") Integer tfomsId,
Model model) {
model.addAttribute("insuranceCompanies", insuranceCompanyService
.getInsuranceCompaniesByTfoms(new TerritorialFondOms(tfomsId)));
return "person/PersonEdit :: insuranceCompany";
}

Categories

Resources