Skip to content Skip to sidebar Skip to footer

Jquery On Change Only Shows The Selected Option, Remove/disable Rest Of Them

Target: From a select dropdown menu, if someone selects an option, disable/remove/hide the rest of the options on that dropdown menu. Here is the dropdown menu. If someone selects

Solution 1:

Keep it simple and use:

$('.selectDropdown').on('change', function(e) {
    $(this).children('option:not(:selected)').prop('disabled', true);
});

In this context, $(this) refers to .selectDropdown and the option elements are the children.

Example Here


..and if you want to remove the unselected children:

$('.selectDropdown').on('change', function(e) {
    $(this).children('option:not(:selected)').remove();
});

Example Here


The reason your code wasn't working was because the option elements are not direct children of the .xyz element. You would have had to use:

$('.selectDropdown').on('change', function(e) {
    $(this).closest('.abc').children('.xyz').children().children('option:not(:selected)').prop('disabled', true);
});

(I simply chained another .children() method after .children('.xyz')..)

Solution 2:

You're over complicating it. Once the user has clicked on the select box, you're inside that selector so there's no need to go up to .abc and .xyz.

Here's a fiddle to show it working in action: http://jsfiddle.net/releaf/ng50zmyo/

$('.selectDropdown').on('change', function(e) {
 $(this).find('option:not(:selected)').prop('disabled', true);
});

Solution 3:

This simplifies things. Since this is the select no need to traverse up 2 levels and back down to get back to where you started again

$('.selectDropdown').on('change', function(e) {
    $(this).children(':not(:selected)').prop('disabled', true);
});

if remove is preferred swap out prop() for remove()

$('.selectDropdown').on('change', function(e) {
    $(this).children(':not(:selected)').prop('disabled', true);
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="abc"><divclass="xyz"><selectname="pqr"class="selectDropdown"><optionvalue='1'>1</option><optionvalue='2'>2</option><optionvalue='3'>3</option><optionvalue='4'>4</option></select></div></div>

Solution 4:

You just select wrong node. $(this).closest('.abc').children('.xyz') --> this node's childs point to select, which has no child node option.

Here you go:

$('.selectDropdown').on('change', function(e) {
    $('select[name="pqr"]').children('option:not(:selected)').prop('disabled', true);
});

JSFiddle

Post a Comment for "Jquery On Change Only Shows The Selected Option, Remove/disable Rest Of Them"