سؤال

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();

    });
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top