Removing a option from DropDownList item with jQuery

大憨熊 提交于 2019-12-13 00:42:18

问题


I have a situation where in some cases a dropdownlist can contain a default value that is not selectable, once another value is changed, the default value should no longer be an option. From what I can tell, this concept does not exist natively, so I am trying to code it up with jQuery. All the DropDownLists which have this condition have a class 'valueSkippedHyperSwap' assigned to them. the value that needs to be removed is the caret '^'. Here is what I have, which is not working:

    $('.valueSkippedHyperSwap').change(function () {
        var node = $(this).has("value='^'");
        node.remove();
    });

per folks request, here is the HTML, though I cannot for the world in me figure out how to get it into a code block:

<!-- snip -->

<div class="questionItem">
<!-- snip -->
<select class="valueSkippedHyperSwap" id="answers_2__Answer" name="answers[2].Answer">
<option selected="selected" value="^">(^) Blank (skip pattern)</option>
<option value="0">(0) No</option>
<option value="1">(1) Yes</option>
<option value="-">(-) Not assessed</option>
</select></div>

<div class="questionItem">
<!-- snip -->
<select class="valueSkippedHyperSwap" id="answers_3__Answer" name="answers[3].Answer">
<option selected="selected" value="^">(^) Blank (skip pattern)</option>
<option value="0">(0) Clear speech-distinct intelligible words</option>
<option value="1">(1) Unclear speech-slurred or mumbled words</option>
<option value="2">(2) No speech-absence of spoken words</option>
<option value="-">(-) Not assessed</option>
</select></div>

<!-- snip -->

One of the key things to note here is that there is more than one input with the valueSkippedHyperSwap class name, so within the event, we have to use the $(this) to fine the correct option, cannot do another search.


回答1:


Assuming your HTML is like this

<select id="dd" class="valueSkippedHyperSwap"> 
    <option value="^">None</option>
    <option value="1">One</option>
    <option value="2">Two</option>    
</select>

The below script should remove item with value ^ if any other options are selected

$(function(){

    $('.valueSkippedHyperSwap').change(function () {
       var item=$(this);
      if(item.val()!="^")
      {
        item.find("option[value='^']").remove();
      }
    });            

});

JsFiddle Sample http://jsfiddle.net/He5gP/10/



来源:https://stackoverflow.com/questions/11005071/removing-a-option-from-dropdownlist-item-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!