I populate a dropdown (dropdown2) based on the user choosing something in a first dropdown (dropdown1). Dropdown1 contains a list of partners and dropdown2 fills a list of people that belong to the partner. This is my jquery code below (it works):
$("select[name='dropdown1']").change(function() {
$.ajax({
type: "POST",
url: "ajax/getPeoplebyPartner",
data: "partnerId="+$("select[name='dropdown1']").val(),
dataType: 'json',
success: function(data){
$("select[name='dropdown2']").empty();
$("select[name='dropdown2']").append($("<option />").val("").text("select the person").attr('selected','selected').attr('disabled','disabled').attr('style','display:none;'));
$.each(data, function() { //Filling each option
$("select[name='dropdown2']").append($("<option />").val(this.id).text(this.name));
});
}
});
});
$("select[name='dropdown1']").change();
However if a user submits the form but there was any error anywhere, dropdown2 is repopulated but the option the user may have made there is lost. I want to fix that.
I think the best way would be to modify this part:
$("select[name='dropdown2']").append($("<option />").val(this.id).text(this.name));
Into:
if(this.id == WHAT THE USER HAD SELECTED BEFORE THE FORM WAS SUBMITTED) $("select[name='dropdown2']").append($("<option />").val(this.id).text(this.name).attr('selected','selected'));
else $("select[name='dropdown2']").append($("<option />").val(this.id).text(this.name));
How can I find what the user had selected before submitting the form?
thanks in advance!