2010-03-11 3 views

Répondre

8

Modifier

Depuis id est unique dans le document pas nécessaire de le relier à l'élément de sélection de parent. Vous pouvez le faire simplement

$("#option1").remove(); 
3

jQuery:

$("#option1").remove(); 

ou

$("#select").remove("#option1"); 

Et la méthode classique javascript:

var option1 = document.getElementById("option1"); 
document.getElementById("select1").removeChild(option1); 
+0

'$ ("# select1")' est inutile. '$ (" # option1 "). remove()' suffira car il est associé à 'id'. –

+1

@Marko: J'étais en train d'éditer cela quand vous avez posté votre commentaire :-) J'ai laissé l'original dans le fait que l'ajout d'identifiants aux tags d'options est assez rare. –

14

Retirer par Valeur:

$("#select1 option[value=1]").remove(); 

Supprimer par le texte:

$("#select1 option:contains(Text)").remove(); 
+0

Pour le texte, «contient» semble être une mauvaise idée, non? Pourquoi ne pas utiliser l'option '$ (" # select1: [text = 'Mon texte'] ")'? –

0

J'ai vu beaucoup de gens avec ce problème. J'ai créé ce script qui pourrait être utile. Espoir vous l'aimez:

var robable = { 
 
    init: function() { 
 
    robable.get_selected_option_from_select(); 
 
    }, 
 
    get_selected_option_from_select: function() { 
 
    $(".robable").off().on("change", function() { 
 
     if ($(this).val() !== "") { 
 
     robable.add_to_list($(this)); 
 
     } 
 
    }); 
 
    }, 
 
    remove_option_from_select: function(select_id, value) { 
 
    $("#" + select_id + " option[value='" + value + "']").remove(); 
 
    }, 
 
    add_option_to_select: function(select_id, value, text) { 
 
    $('#' + select_id).append('<option value="' + value + '">' + text + '</option>'); 
 
    }, 
 
    add_to_list: function(select) { 
 

 
    option_text = $(".robable option[value='" + select.val() + "']").text(); 
 

 
    //Add to list 
 
    $('#list').append("<li data-value='" + select.val() + "' data-text='" + option_text + "'><a href='#' class='filter-remove' data-parent-id='" + select.attr("id") + "'>Delete</a> " + option_text + "</li>"); 
 
    robable.remove_from_list(); 
 

 
    //Remove from select 
 
    robable.remove_option_from_select(select.attr("id"), select.val()); 
 
    }, 
 
    remove_from_list: function() { 
 
    $(".filter-remove").off().on("click", function() { 
 
     var select_id = $(this).data('parent-id'); 
 
     var option_value = $(this).closest("li").data('value'); 
 
     var option_text = $(this).closest("li").data('text'); 
 

 
     //Add to select 
 
     robable.add_option_to_select(select_id, option_value, option_text); 
 

 
     //Remove from list 
 
     $(this).closest("li").remove(); 
 
    }); 
 
    } 
 
}; 
 

 
robable.init();
<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <title>Select Robables</title> 
 
</head> 
 

 
<body> 
 
    <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> 
 

 
    <ul id="list"></ul> 
 

 
</body> 
 

 
</html>

Questions connexes