Answer the question
In order to leave comments, you need to log in
How to use the onchange select event to fill 3 inputs at once?
Quite recently I started to study ASP.NEt MVC, I'm going to make a web interface for calculation. There is a SQL database (local) from which I pass the names of cities and the corresponding thermal characteristics (T_ext, Z_ht, T_ht) to the select tag using the foreach loop and ViewBag, in which I store the data. And so, it is necessary for me onchange in selecte to fill with the corresponding data three input fields.
I tried with getelementbyid, it turns out to display the value of only one parameter in one input.
The select itself:
Выберите город,в котором планируете строительство:
<select id="select" onchange="">
<option selected="selected">Выберите город</option>
@foreach (var b in ViewBag.cities)
{
<option>@b.Name</option>
}
</select>
Answer the question
In order to leave comments, you need to log in
On server
<select id="select">
<option selected="selected">Выберите город</option>
@foreach (var b in ViewBag.cities)
{
<option value='@JsonConvert.SerializeObject(b)'>@b.Name</option>
}
</select>
$('#select').change(function(){
var $val = $(this).find('option:selected').val();
if(!$val) return;
var obj = JSON.parse($val); // здесь js объект с вашими полями
// и здесь его можно обработать и заполнить свои инпуты
var t_ext = obj.T_ext;
var t_ht = obj.T_ht;
var z_ht = obj.Z_ht;
$('input#T_ext').val(t_ext); // Добавил исходя из Ваших комментариев других ответов
$('input#Zht').val(t_ht);
$('input#Tht').val(z_ht);
});
You have all options with the same value value. Yes, for reference . And now my key question - what happens in the onchange event, which you did not show here? Suppose you have option:selected. What do you take from there? title? Or do you want to get some more values on the client side by name from the ViewBag? I have bad news for you - you can’t do this, and I’m 99% sure that it’s impossible. This is a server object.
If I understand you correctly, you can't take three values at once? If yes, then there are several solutions for you:
1. in each option tag, write three hidden input fields that will contain these values:
On the onchange event, you simply look at which element was selected and take the values from the hidden fields.
2. option through js array. create an array of objects and stuff all the values into it. then, for each option, set a value that will correspond to an array element. well, at the onchange event, you take the value and pull out the array object by index.
I could say more if you provided your onchange event and the input fields in question.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question