Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing select options with javascript on change

Before you -1 this for being such a simple question read further, because ive spent a while searching and cant figure it out. What i have is 5 select boxes. Each ones results depend on what is selected before it. There is no submit button. I just need the to change based on whats selected in the previous box and so far i have that. Oh and the results are being pulled from a database. The problem is when you select an option in lets say box 1, box 2 options appear, but when you go and select an option in box 1 again, they options are just stacked on the others. I need them to clear when its changed again. I'll post the js i have and if you need anything else just ask.

p.s. im getting the options using php-mysql. p.s.s this site has to be finished by tomorrow so im kinda in a rush. Please dont waste time telling me this is a stupid question or what not.

Thanks in advance for the help.

$(function () { //When the page is finished loading run this code
    $('#country').change(function () {
        $.ajax({
            url: "<!--Base url taken out-->/discovery/aLoad",
            success: function (data) {
                eval(data);
            },
            error: function () {
                alert('failed');
            },
            data: {
                country: getSelectValues('#country')
            },
            type: 'POST'
        });
    });
 });

     function changeSearchBar (newBar) {
    //remove the crap
    function ClearOptions(country)
    {
    document.getElementById('country').options.length = 0;
    }

    for (var i = 0; i <= newBar.length; i++) {
        newBar[i].id = newBar[i][0];
        newBar[i].name = newBar[i][1];
        $('#group').append(
            $('<option></option>').attr('value', newBar[i].id).text(newBar[i].name)
        );
    }
     }

     function getSelectValues (sId) {
    var str = "";

    $(sId +" option:selected").each(function () {
        str += $(this).val() + ",";
    });

    return str.replace(/.$/g, '');
}
like image 353
Dylan Buth Avatar asked Nov 13 '22 09:11

Dylan Buth


1 Answers

From what I understand from your long post you just need to remove all select child's before starting to append the new option from the AJAX request.

Try something like this before your for loop:

$('#group').html('');​

Demo: http://jsfiddle.net/57TYu/2/

like image 100
Rui Carneiro Avatar answered Nov 16 '22 02:11

Rui Carneiro