1

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 ?

        });
    });

3 Answers 3

3

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

i will accept your code as the best answer.Thanks for help.I would like to learn one more something. If my table id is "MyTableID" , how would code be . How can i use table id in stead of "table select" ?
@user3409638: You can specify the id in the selector as well, such as #MyTableID select. Separating selector elements by a space simply means that the latter elements are descendants of the former elements.
1

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

1 Comment

how can i do this by using foreach ? i do not want to set one by one.
0

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

    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.