Reputation: 127
I want to click a button on a razor page that set values for two input fields "on the client side".
I have two input fields
<input id="pageBatteryName" name="pageBatteryName" asp-for="Firmware.BatteryName" class="form-control" />
<select id="pageDeviceId" name="pageDeviceId" asp-for="Firmware.DeviceId" class ="form-control" asp-items="ViewBag.DeviceId"></select>
A button
<input type="button" onClick="AutoFill()" value="Auto Fill"/>
and a javascript
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
function AutoFill()
{
var vBatteryName = document.getElementsByName('pageBatteryName');
vBatteryName.value = "QWERTY1234";
var vDeviceId = document.getElementsByName('pageDeviceId');
vDeviceId.value = 2;
vBatteryName.dispatchEvent(new Event('change'));
vDeviceId.dispatchEvent(new Event('change'));
}
</script>
}
The code above do not work. I spend a day trying to do that. Could You help me please?
If the button works I will set the inputs based on selected input file name (nearly all of input fields for my form). I used OnPostAutoFill post c# method but it reloads a page and I found that javascript can be usefull here. If javascript is not suitable for this task, can you show me the way?
Upvotes: 0
Views: 1967
Reputation: 39898
getElementsByName
returns an array of elements. Instead, you can use getElementById
to get a single element:
var vBatteryName = document.getElementById('pageBatteryName');
vBatteryName.value = "QWERTY1234";
This works for an input field.
For a select, you want to add option elements to the select like this:
var opt = document.createElement('option');
opt.value = 0;
opt.innerHTML = 1;
vDeviceId.appendChild(opt);
See this jsfiddle to see your code in action: https://jsfiddle.net/12xndyLo/
Upvotes: 1