I am working on a .Net Asp Core Razor Page project and I want to have a dropdown and when I select one option of the dropdown it will be displayed on the input.
Here is the code for the dropdown:
<div class="input-group">
<input type="text" class="form-control" id="result">
<div class="input-group-append">
<button class="btn btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
</button>
<div class="dropdown-menu form-control">
<select asp-for="MyList" asp-items="@Model.MyList" required="" id="selectedOption">
<option value="" selected="">-- Select --</option>
</select>
</div>
</div>
</div>
And here is the code for jQuery:
<script type="text/javascript">
$(document).ready(function () {
$('#selectedOption').change(function () {
var selectedValue = $(this).val();
$('#result').val(selectedValue);
});
});
</script>
The problem is that when I select an option from the dropdown, it is not displayed on the input field. Is there any other way I can obtain the desired behaviour?
SOLUTION
@section scripts{
<script type="text/javascript">
$('#selectedOption').change(function () {
var selectedValue = $(this).val();
$('#result').val(selectedValue);
});
</script>
}
I forgot to add the @section, now my code is working fine
Try with the following code snippet: Controller code for dropdown data
var MyList = new List<SelectListItem>
{
new SelectListItem { Value = "1", Text = "ONE" },
new SelectListItem { Value = "2", Text = "TWO" },
new SelectListItem { Value = "3", Text = "THREE" },
new SelectListItem { Value = "4", Text = "FOUR" },
new SelectListItem { Value = "5", Text = "FIVE" }
};
Razor code:
<div class="input-group">
<input type="text" class="form-control" id="result">
<div class="input-group-append">
<button class="btn btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
</button>
<div class="dropdown-menu form-control">
<select asp-for="MyList" asp-items="@Model.MyList" required="" id="selectedOption">
<option value="" selected="">-- Select --</option>
</select>
</div>
</div>
</div>
Jquery part changed to :
<script type="text/javascript">
$('#selectedOption').change(function () {
var selectedValue = $(this).val();
$('#result').val(selectedValue);
});
</script>