StackTrace
StackTrace

Reputation: 9416

Find previously selected value of drop down list on change event

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?

Upvotes: 0

Views: 4163

Answers (2)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93571

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

Upvotes: 2

Torbjørn Angeltveit
Torbjørn Angeltveit

Reputation: 2322

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

Upvotes: 2

Related Questions