1

How to set the selected value of a dropdownlist to the selected value of another?

The below code shows how to accomplish this correctly.

ASPX

<asp:DropDownList ID="ddl1" RunAt="Server" DataValueField="ID" DataTextField="ID" AppendDataBoundItems="true"/>
<asp:DropDownList ID="ddl2" RunAt="Server" DataValueField="ID" DataTextField="TEXT" AppendDataBoundItems="true"/>

JQUERY

$("#<%= ddl1.ClientID %>").change(function() {
    var Code = $(this).val();
    $("#<%= ddl2.ClientID %>").val(Code);
});

When using jQuery Mobile, however the DataTextField is rendered as a span tag which the above code does not update.

QUESTION

How to amend the above code to accommodate for this?

http://jsfiddle.net/E28WW/

Omar
  • 32,302
  • 9
  • 69
  • 112
DreamTeK
  • 32,537
  • 27
  • 112
  • 171

2 Answers2

1

Store the value from first selectmenu, then look for it in the second one. Select it using .prop('selected', true); and then call .selectmenu('refresh').

Demo

$(document).on('pageinit', function () {
  $(document).on('change', '#ddl1', function () {
    var selected = $(this).val();
    $('#ddl2 option[value="' + selected + '"]').prop('selected', true);
    $('#ddl2').selectmenu('refresh');
  });
});

I used pageinit which is equivalent to .ready(). It is a special event for jQM.

Omar
  • 32,302
  • 9
  • 69
  • 112
0

Have you checked that the change function is actually being called. Is the script you provide the entire contents of the script tag?

The function will not be bound to the event until it is loaded, using the $(document).ready(); will bind the event to the control.

$(document).ready(function() {
    $("#<%= ddl1.ClientID %>").change(function() {
        var Code = $(this).val();
        $("#<%= ddl2.ClientID %>").val(Code);
    });
});
Nunners
  • 3,047
  • 13
  • 17
  • Yes this is all the script for this page. Debugging shows the val() is being set correctly and $ is shorthand for $(document).ready in Jquery. – DreamTeK Oct 04 '13 at 09:45
  • 1
    Please use JQM page events like pageshow etc.. for element events – Sheetal Oct 04 '13 at 10:30
  • Apologies didn't realize that this was a JQM question. – Nunners Oct 04 '13 at 10:32
  • No my apologies Nunners, for not being clear in my question initially. I did not believe it was relevant to the question however it seems it is the cause of the problem. – DreamTeK Oct 04 '13 at 10:35
  • @DreamTeK on jsfiddle it works, in reality, it will mess up your code. http://stackoverflow.com/questions/14468659/jquery-mobile-document-ready-vs-page-events – Omar Oct 04 '13 at 10:35
  • Thanks for pointing this out @Omar however it is not relevant in my situation as I have ajax navigation disabled due to conflicts with asp.net. – DreamTeK Oct 04 '13 at 10:40
  • No apologies needed. @DreamTeK jQM events still fire in absence of ajax navigation :) – Omar Oct 04 '13 at 10:48