Zapnologica
Zapnologica

Reputation: 22556

Basic java script to get combobox

I am just starting out with some java script in an asp.net mvc web site.

I current have a form which I am working on.

The first field which the user is prompted with is a combobox / select (in html)

here is the code for it:

<select name="select">

@foreach (var item in Model.networks)
 {
   <option value="">@Html.DisplayFor(modelItem => item.name)</option>
 }
</select>

Now my next field depends on the option which they chose from the combo box.

How can I populate the next field based on the option they chose in the combo box?

So when the user navigates to the page they will ave a combo box populated with all the options. Below that will be empty fields. When the user selects a option in the combo box I want it to then populate the empty fields with the corresponding data from the option which was chosen.

How do I go about doing this?

Please give the newby answer as in the method in which it will be done. I am assuming that I will be using java script for it?

Upvotes: 1

Views: 299

Answers (3)

Rui
Rui

Reputation: 4886

If I understand your question correctly you want to react to a combo box value changing and display different content in your page.

If that is the case what you need to know is

  • how to handle the change event in the select (drop down)
  • populate empty fields

Here's how you can register and handle the change event in the dropdown:

$("select[name='select']").on("change", function(){
    $('#input1').val("What you want in the input goes here");
});

Here's a fiddle that demonstrates this.

Upvotes: 0

Jelle Oosterbosch
Jelle Oosterbosch

Reputation: 1742

Put the onChange="getSelectedValue" attribute of the select element and then use the following javascript.

<script>
function getSelectedValue(sel)
    {
        txtToFill.Text(sel.options[sel.selectedIndex].text);
    }
</SCRIPT>

Upvotes: 0

ˈvɔlə
ˈvɔlə

Reputation: 10242

Although I cannot understand your question in detail, I hope I can help you.

HTML

If you have a select element that looks like this:

<select id=dropdown>
  <option value="1">test1</option>
  <option value="2" selected="selected">test2</option>
  <option value="3">test3</option>
</select>

Plain Javascript solution

Running this code:

var element = document.getElementByID('dropdown');
var current = e.options[e.selectedIndex].value;

Would make current be 2. If what you actually want is test2, then do this:

var e = document.getElementById('dropdown');
var strUser = e.options[e.selectedIndex].text;

Which would make current be test2

Upvotes: 1

Related Questions