Oli
Oli

Reputation: 2587

how to add / remove values in a drop down list using jquery

I have a 2 drop down lists with that same values and the values are populated by database values. The problem I am trying to solve is that the 2 drop down boxes cannot have the same value when the form is submitted. The POST values must be different.

If the user selects option A from dropdown box A, I would like to remove option A from drop downdrop box B. If the user then selects option B from dropdown box A, I would like option A to be put back in dropdown box B and the new value option B to be removed from dropdown box B.

I have tried a couple of different ways to do this, the closest being the following code. This bit does what I want when the page loads.....

$(document).ready(function() {
    $.dropdownAcache = { 
        val : "",
        val1 : "",
    };

    $('#id_A').ready(function() {
        var optionval = $('#id_A').val();
        $.dropdownAcache.val = $('#id_A').val();
        $('#id_B > option[value=' + optionval + ']').remove();
    });

    $('#id_A').click(function() {
        var optionval = $('#id_A').val();
        $.dropdownAcache.val1 = $('#id_A').val();
        $('#id_B > option[value=' + optionval + ']').remove();
        $('#id_B').append$(dropdownAcache.val);
        $.dropdownAcache.val = $.dropdownAcache.val1;
    });

.... but all it seems to do is remove the values from dropdown box B but never adds the values back in. It's actually quite comical as I end up with no values in dropdown box B, but in all seriousness can anyone help to get this working?

Cheers - Oli

Upvotes: 0

Views: 2631

Answers (1)

nbrooks
nbrooks

Reputation: 18233

The event you should be using is the 'change' event. Also, you don't need the second .ready() callback, it serves no purpose (the first .ready() handles that)

$.dropdownAcache = { 
    val : "",
    val1 : ""
};

$(document).ready(function() {

    var optionval = $('#id_A').val();
    $.dropdownAcache.val = $('#id_A').val();
    $('#id_B > option[value="' + optionval + '"]').remove();

    $('#id_A').change(function() {
        optionval = $('#id_A').val();
        $.dropdownAcache.val1 = optionval;
        $('#id_B > option[value="' + optionval + '"]').remove();
        $('#id_B').append( $.dropdownAcache.val );
        $.dropdownAcache.val = $.dropdownAcache.val1;
    });
});

(As for why your list never gets the values added back, you have an unfortunately placed typo .append$(dropdownAcache.val);)

Upvotes: 1

Related Questions