简体   繁体   中英

Javascript change event for html.dropdownlist

I am beginner on javascript .

I try to use Html.Dropdownlist in Asp.net Mvc.

I have 1 dropdownlist and other 4 dropdownlists.

If 1.dropdownlist change value , i want to apply 1.dropdownlist value for 4 dropdownlists by using foreach in javascript.

Html:

@Html.DropDownList("MainDropDownList", listItems, "Select", new { @id = "MainDropDownListID" }) 

// İf this dropdownlist value changes , i want to apply value to other dropdownlists.

<table>
    <tr>
        <td>@Html.DropDownList("MyDropDownList1", listItems)</td>
        <td>@Html.DropDownList("MyDropDownList2", listItems)</td>
        <td>@Html.DropDownList("MyDropDownList3", listItems)</td>
        <td>@Html.DropDownList("MyDropDownList4", listItems)</td>
    </tr>
</table>

Javascript:

  $(function () {
        $('select#MainDropDownListID').change(function () {
            var SelectedValue = $(this).val();

         //How can i apply selectedvalue to 4 dropdownlists value using foreach ?

        });
    });

jQuery's .val() function can also be used to set a value by supplying the value as an argument :

$('#MainDropDownListID').change(function () {
    var SelectedValue = $(this).val();
    $('table select').val(SelectedValue);
});

Firstly you would need to access the dropdown correctly - #MainDropDownListID for ID

Then just set the value

$(function () {
    $('#MainDropDownListID').change(function () {
        var SelectedValue = $(this).val();
        $('#MainDropDownList1").val(SelectedValue);
        $('#MainDropDownList2").val(SelectedValue);
        $('#MainDropDownList3").val(SelectedValue);
        $('#MainDropDownList4").val(SelectedValue);
    });
});

or in one go

$('select[id^"MainDropDownList"]').val(SelectedValue);

Or using each:

$("table").find('select[id^"MainDropDownList"]').each(function() { 
 $(this).val(SelectedValue);
});

Assign an unique id to each dropdown and do as below:

<td>@Html.DropDownList("MyDropDownList1", listItems,new {id="ddl1"})</td>

     $("#ddl").change(function()
    {
       var SelectedValue = $(this).val();

    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM