0

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!

4

1 回答 1

0

You have two options:

  1. After the user submitted the form - using the server side you will need to analyze the content of the POST header - or if your form use GET, you will need to parse the querystring (that's something that you can also do using javascript)
  2. You validate your form without the 'submit' action but by using an Ajax call. This Ajax call can return you an error code based on the error made by the user and then you can update the user interface accordingly.

I recommend the second option. You have a good example here: http://jqueryfordesigners.com/using-ajax-to-validate-forms/

于 2013-03-30T17:31:10.417 回答