0
function LoadData(id) {
var employeeId = $.trim($("#employeeId").val());
var employeeType = $.trim($("#employeeType").val());

var obj = "";
var CityId = $.trim($("#ddlCity").val());
obj = new ViewModel1(employeeId, employeeType, 0, $.trim($("#DeptName").val()), "", "", $.trim($("#SectionName").val()), CityId);
var postedData = JSON.stringify(obj);

Loader();
$.ajax({
    //...........
    //...........
})

}

I have the above function and i want to get the previously selected value in the element #ddlCity. The above function is called from the line below.

@Html.DropDownGroupListFor(m => m.CityId, Model.GroupedTypeOptions, new { name = "ddlCity", id = "ddlCityName", @onchange = "javascript:LoadData(this.value)" })

var CityId = $.trim($("#ddlCity").val()); is giving me the CityId of my new selection in the dropdownlist.

So how can i get the CityId of the previously selected value?

StackTrace
  • 9,190
  • 36
  • 114
  • 202

2 Answers2

2

I would store it in an attribute in the select tag.

Say this is your html

`<select data-last-selection>
 ...
 </select>`

Now add something like this to your javascript

$("[data-last-selection]").change(function() {
    var previousData = $(this).data("lastSelection");
    $(this).data("lastSelection",$(this).val());

    // Handle the previous data now stored in previousData variable
});
Torbjørn Angeltveit
  • 2,232
  • 2
  • 13
  • 10
2

Might as well post my comment as answer (too:).

Have onchange store the new value as a data- attribute/data-storage on the select element. You can then pick it up in subsequent changes.

e.g. http://jsfiddle.net/TrueBlueAussie/bLc12tu0/

$(".selector").change(function() {
    // Get the previous value (if any)
    var prev = $(this).data("prev");
    // Store the new value for next time
    $(this).data("prev",$(this).val());

    $('#output').html(prev);
}).each(function(){
    // Also save any initial dropdown value as the previous value (for each select)
    $(this).data("prev", $(this).val());
});
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
  • 1
    Probably also want to set the `data-prev` value when the page is first loaded `$(".selector").data("prev", $(this).val());` –  Nov 28 '14 at 03:17
  • Not if the value has been set by model binding (e.g. using `DropDownListFor()`) and you can even see it in your own fiddle (the initial value is `1` but if you select another item, the previous value does not show `1` –  Nov 28 '14 at 07:56
  • @Stephen Muecke: Thanks for the suggestion. I have updated with a transparent fix that will support multiple controls. – iCollect.it Ltd Nov 28 '14 at 09:28