anouar
anouar

Reputation: 317

How to remove an item from a DropDownList basing on the item selected in another DropDownList in ASP MVC and using Javascript

I am developing an ASP .Net MVC 3 application using C# and SQL Server 2005.

In a view, I have two dropdownlist which loads same values from a table in the base.

I want create an event that delete the item selected in the DropDwonList 1 from the DropDownList 2.

This is the code :

<%:Html.Label("Poste :")%><%: Html.DropDownListFor(model => model.SelectedPoste, Model.PostesItems, new { @id = "poste" })%>

<%:Html.Label("Poste Suivant :")%><%: Html.DropDownListFor(model => model.PosteSuivantSelected, Model.NextPS, new { @id = "dd" })%>

So basing on the code above, when the item is selected in 'Poste',,,its similair should be deleted from 'Poste Suivant'.

This is what I try but it's not worked :

function test3() {
    var dd = document.getElementById('dd');
    var posteElement = document.getElementById('poste');
    var currentIndexP = posteElement.selectedIndex;
    var currentIndexD = dd.selectedIndex;
    if (currentIndexP == currentIndexD) dd.removeChild(dd[currentIndex]);

} 

I think the problem is : because I didn't define 'test3()' in the dropdownlist.

Upvotes: 0

Views: 2405

Answers (1)

Sean Airey
Sean Airey

Reputation: 6372

You can just add the onchange attribute like you have done with the id attribute in your HTML helper:

<%:Html.Label("Poste :")%><%: Html.DropDownListFor(model => model.SelectedPoste, Model.PostesItems, new { @id = "poste", onchange = "test3()" })%>

<%:Html.Label("Poste Suivant :")%><%: Html.DropDownListFor(model => model.PosteSuivantSelected, Model.NextPS, new { @id = "dd" })%>

Add an onload attribute to the body tag so that the function runs to remove the default selected item:

<body onload="test3()">

Then if we modify the javascript so that it removes the item from the second list based on value instead of index and add some code to store the lost option to add back in, everything should work nicely:

var removedOption = null;
var removedOptionIndex = -1;

function test3() {
    var dd = document.getElementById('dd');
    var posteElement = document.getElementById('poste');
    var currentValue = posteElement.options[posteElement.selectedIndex].value; // this will be the value of the selected option, '2' in this case: <option value="2">Two</option>
    var currentText = posteElement.options[posteElement.selectedIndex].text; // this will be the text of the selected option, 'Two' in this case: <option value="2">Two</option>

    // add the previously removed option back into the list in its previous position
    if (removedOption != null) {
        var newOpt = document.createElement("option");
        newOpt.value = removedOption.value;
        newOpt.innerHTML = removedOption.text;
        if (removedOptionIndex < 0) removedOptionIndex = 0;
        if (removedOptionIndex > dd.options.length) removedOptionIndex = dd.options.length;
        insertOptionToSelect(dd, removedOptionIndex, newOpt);
        removedOption = null;
    }

    for (var i = 0; i < dd.options.length; i++) // loop through all of dd's options
    {
        if (dd.options[i].value == currentValue) // use this if you want to compare by value
        {
            removedOption = dd.options[i];
            removedOptionIndex = i;
            dd.removeChild(dd.options[i]);
            break;
        }
        if (dd.options[i].text == currentText) // use this if you want to compare by text
        {
            removedOption = dd.options[i];
            removedOptionIndex = i;
            dd.removeChild(dd.options[i]);
            break;
        }
    }
}

function insertOptionToSelect(select, idx, option) {
    var saved = [];
    var i;
    for (i = 0; i < select.options.length; i++) {
        saved.push(select.options[i]);
    }
    select.options.length = 0;
    for (i = 0; i < idx; i++) {
        select.options[select.options.length] = saved[i];
    }
    select.options[select.options.length] = option;
    while (i < saved.length) {
        select.options[select.options.length] = saved[i++];
    }
}

Credit to pizzamonster for his answer to this question How to insert option at specified index of select(Multiple) in html? and his insertOptionToSelect function.

To compare by value or text just use the appropriate if statement and feel free to remove the other variable for tidiness. I gave you both options as I'm new to MVC myself and I'm not 100% sure about the rendered HTML =]

Upvotes: 1

Related Questions