Sam Carleton
Sam Carleton

Reputation: 1408

Removing a option from DropDownList item with jQuery

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.

Upvotes: 1

Views: 2619

Answers (1)

Shyju
Shyju

Reputation: 218962

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/

Upvotes: 2

Related Questions