how to get selected value of dropdown in reactive form - angular-reactive-forms

I am trying to get the selected value of the dropdown on change event to be sent on reactive form submission. I have a very similar scenario working for radio based on the answer from how to get selected value of radio in reactive form
Here's the code for dropdown
<div class="row" *ngIf="question.controls.type.value === 'dropdown'">
<div class="col-md-12">
<div class="form-group__text select">
<label for="type">{{ question.controls.label.value }}</label>
<br><br>
<select name="value" formArrayName="component" (change)="updateSelection(question.controls.component.controls, $event.target)">
<option
*ngFor="let answer of question.controls.component.controls; let j = index" [formGroupName]="j"
[ngValue]="answer?.value?.value">
{{answer?.value?.value}}
</option>
</select>
</div>
</div>
</div>
I am not able to pass the answer as formcontrol to updateSelection on change of a selected option from the dropdown. Any help is greatly appreciated.
https://stackblitz.com/edit/angular-acdcac

Very similarily like previous question, we iterate the form controls in your array, initially set all as false, and then turn the chosen choice as true. So template let's pass $event.target.value:
<select name="value" formArrayName="component"
(change)="updateSelection(question.controls.component.controls, $event.target.value)">
<option *ngFor="let answer of question.controls.component.controls; let j = index" [formGroupName]="j"
[ngValue]="answer?.value?.value">
{{answer?.value?.value}}
</option>
</select>
And in the component we as mentioned iterate the form controls and set all as false. The value for $event.target.value will be the string value, for example Choice 1. We then search for the form control that has that value and then set the boolean for that particular formgroup:
updateSelection(formArr, answer) {
formArr.forEach(x => {
x.controls.selectedValue.setValue(false)
})
let ctrl = formArr.find(x => x.value.value === answer)
ctrl.controls.selectedValue.setValue(true)
}
Your forked StackBlitz

Related

Need to show the down arrow in dropdown list in ASP.NET Core MVC

Working on an ASP.NET Core 6 MVC app. I am created a dropdown using the select asp-for tag helper. But I am not seeing a dropdown down arrow. Also I want to set the top or particular value selected by default.
Below is code and image of a dropdown
<div class="col-sm-3">
<select name="products" class="form-control "
asp-items="#(new SelectList(ViewBag.ddaircraft,"id","name"))">
</select>
</div>
Action Method code for ViewBag:
Public IActionResult Index()
{
var countries= _countries.getCountries();
//add an country item on the top of list.
countries.Insert(0, new Aircraft { Registration="0"});
//i used the country.name for value and item
var ddforAircraft = from country in countries
select new { id = country.name, name=country.name=="0"?"Item List":country.name };
// ddforAircraft.Append(new { id = "0", name = "" });
ViewBag.ddaircraft = ddforAircraft;
return View()
}
I found the answer, after Tiny Wang pointed me to the direction which really helped me to search the answer.
In order to see the dropdown down arrow I added a css class "form-select" without removing anything and I started to see the down arrow
<div class="col-sm-3">
<select name="products" class="form-control form-select-sm form-select " asp-items="#(new SelectList(ViewBag.ddaircraft,"id","name"))">
</select>
</div>
Missing dropdown arrow resulted from the class form-control, I test in my side and I found the arrow can be seen by default until I add class="form-control " to my code:
removing this 2 options then the arrow appeared again, so it proved to relate to the class, you may need to update the style:
Then I use Jquery to change the default selected option when page is loading in my code, my selector has Id Country, then change the value(ListItem.Value):
<select asp-for="Country" asp-items="#(new SelectList(Model.Countries, nameof(ListItem.Value), nameof(ListItem.Text)))">
<option>Please select one</option>
</select>
#section Scripts{
<script>
$("#Country").val('Canada')
</script>
}

Get DropDownList value into POST method

I am working on this ASP.NET Core MVC where I have this DropDownLisit which gets its values from Controller using ViewBag.DishTypes. However, upon submitting the form, the POST method is not getting the value of the option selected in the DropDownList. The code snippets are as follows:
Controller: GET Method
var allDishTypes = _context.DishType
.ToList()
.Select(dt => new SelectListItem { Value = dt.DishTypeId.ToString(), Text = dt.DishTypeName.ToString() }).ToList();
ViewBag.DishTypes = allDishTypes;
return View();
View
<form asp-controller="Home" asp-action="AddMenuItems">
<div class="row">
<label class="my-1 mr-2" for="inlineFormCustomSelectPref">Dish Type</label>
<div class="input-group">
<div class="fg-line form-chose">
<label asp-for="DishTypeId" class="fg-labels" for="DishTypeId">Dish Type</label>
<select asp-for="DishTypeId" asp-items="ViewBag.DishTypes" class="form-control chosen" data-placeholder="Choose Dish Type" required name="dishtype" id="dishtype">
<option value=""></option>
</select>
</div>
</div>
....
Controller: POST Method
[HttpPost]
public IActionResult AddMenuItems([Bind("DishTypeId, DishName, Cost")] Dishes dishesObj)
{
....
}
the POST method is not getting the value of the option selected in the DropDownList
Note that you specified a name=dishtype within your code. By this way, the field name is
always the same as this name attribute, i.e, dishtype instead of DishTypeId, which will not be recognized by ASP.NET Core by default.
To fix that issue, simply remove that attribute such that it uses asp-for to generate the name attribute automatically:
<select asp-for="DishTypeId" asp-items="ViewBag.DishTypes"
class="form-control chosen" data-placeholder="Choose Dish Type" required
name="dishtype" id="dishtype"
>
<option value=""></option>
</select>

Capybara Datalist Select not visible

I have the following HTML snippet:
<input type="text" id="manufacturer" list="manufacturers" placeholder="Search by manufacturer name or supplier code" class="form-control form-control-2-3" value="" name="manufacturer">
<datalist id="manufacturers">
<select>
<div>
<option value="Jaguar">AA</option>
<div></div>
</div>
<div>
<option value="Audi">AB</option>
<div></div>
</div>
<div>
<option value="Mercedes">AC</option>
<div></div>
</div>
</select>
</datalist>
It's a dropdown menu and I want to select one of the options. No matter what I try with any find command or select function. I always get the same error:
Selenium::WebDriver::Error::ElementNotVisibleError: element not visible: Element is not currently visible and may not be manipulated
Does anyone have any suggestions on how to scope to those options and select one?
Thanks.
What you're trying to do isn't currently possible because it's not actually a dropdown select element. The <datalist> option elements are never actually visible on the page because the standard states "In the rendering, the datalist element represents nothing and it, along with its children, should be hidden." - https://html.spec.whatwg.org/dev/form-elements.html#the-datalist-element . Instead any <option> elements in the datalist are just used as autofill suggestions for the input element (but don't actually restrict the value a user can input in any way). Because of this and since the datalist user can just type anything they want into the input element you can set the input value like any other text input.
fill_in("manufacturer", with: 'Jaguar')

Sending form field values to params hash - rails

I have a partial that I call in layouts/application.html.erb to display a form for a search. The user chooses values from the two select fields; then, should hit enter to render a view with search results.
Here is the partial:
** _search.html.erb:
<form name="classic">
<select name="countries" size="1" onChange="updatecities(this.selectedIndex)" style="width: 150px">
<option selected>Select A Brand</option>
<option value="usa">Opel</option>
<option value="canada">Cheverolet</option>
<option value="uk">Scoda</option>
</select>
<select name="cities" size="1" style="width: 150px">
</select>
</form>
<script type="text/javascript">
var countrieslist=document.classic.countries
var citieslist=document.classic.cities
var cities=new Array()
cities[0]=""
cities[1]=["Vectra|vectravalue", "Corsa|corsavalue"]
cities[2]=["Optra|optravalue", "Lanos|lanosvalue"]
cities[3]=["Octavia|octaviavalue", "Fleshia|fleshiavalue"]
function updatecities(selectedcitygroup){
citieslist.options.length=0
if (selectedcitygroup>0){
for (i=0; i<cities[selectedcitygroup].length; i++)
citieslist.options[citieslist.options.length]=new Option(cities[selectedcitygroup][i].split("|")[0], cities[selectedcitygroup][i].split("|")[1])
}
}
</script>
The javascript is just to filter the second select dropdown based on the first select dropdown. What I need to do is to send the values chosen in this form in the URL for params hash so that I can act on it in the controller and display the search results. I could use link_to.
How do I include the selected values from the form fields in link_to?
Your help is appreciated. Thanks!
Serialize the form and send the data to the server. The selected value is passed as the hashvalue where the key is the "id" for the select tag.

jQuery Prev() Question

Sorry guys, I should have posted the script directly without cleaning it. Please check the updated script, it should now clear things up. Thanks!
Consider the following JavaScript :
var selected = 0;
var options = 0;
$('.newListSelected').each(function() {
selected = $(this).children('.selectedTxt');
selected = selected.text();
/* Everything before this line works completely fine */
options = $(this).prev();
options.find('option[value=' +selected+ ']').attr('selected', 'selected');
}).remove();
And HTML :
<select name="type[]" style="display: none;">
<optgroup>
<option value="none">Select</option>
</optgroup>
<optgroup label="First Group">
<option value="1">One</option>
<option value="2">Two</option>
</optgroup>
<optgroup label="Second Group">
<option value="10">Ten</option>
<option value="20">Twenty</option>
</optgroup>
</select>
<div class="newListSelected">
<div class="selectedTxt">20</div>
<ul class="newList">
<!-- Other stuff here -->
</ul>
</div>
What I'm trying to do actually is adding the selected attribute to the corresponding select option that has the same value as the text in .selectedTxt. In the code above, it should add selected="selected" to <option value="20">Twenty</option>.
However its not performing as expected, I also tried adding alert(option); below prev(); but it didn't output anything useful.
Thanks.
The Javascript works fine, as can be seen here: http://jsfiddle.net/4HsXp/
If you need to be able to select multiple items in a select element, you need to set the multiple and size attribute, like this:
<select multiple="multiple" size="2">
<option>1</option>
<option>2</option>
</select>
See: http://reference.sitepoint.com/html/select
Edit:
Attaching console.log statements to the new code still does not any problem. Running it on jsfiddle gave me the correct output:
jQuery(select)
Original Value: none
New Value: 20
I'm not sure what you are trying to do, but why couldn't you just select all option elements with proper selectors? If you want to select only some options, then you have to add extra selector attrbiutes.
$('select option').each(function() {
$(this).attr('selected', 'selected');
});

Resources