haltman
haltman

Reputation: 551

jquery block <select> to first option

I've a code like this:

<select name="aa">
    <option>a</option>
    <option>b</option>
    <option>c</option>
</select>

There is a way to stop opening select of all my form and make show only first select in this example only a?

Thanks in advance ciao h

Upvotes: 4

Views: 11063

Answers (4)

Caspar Kleijne
Caspar Kleijne

Reputation: 21864

remove all other options with the :gt(0) filter (0) is the index like this:

 $("select[name='aa'] option:gt(0)").remove();

or disable them like this:

 $("select[name='aa'] option:gt(0)").attr("disabled", "disabled");

and select an item with the :eq(0) filter (0) is the index like this:

 $("select[name='aa'] option:eq(0)").attr("selected", "selected");

the reverse can be done with a :not filter:

$("select[name='aa'] :not(option:gt(0))").attr("disabled", "disabled");

or a :lt filter:

$("select[name='aa'] option:lt(1)").attr("disabled", "disabled");

just assign an empty string .attr("disabled", ""); or .attr("selected", ""); to remove an attribute setting.

fiddle here

to flip/flop values I think you need a second (hidden) select:

fiddle here

// hide items
var src = $("select[name='aa'] option:eq(0)");
var tar = $("select[name='ab']").hide();

tar.append(src.clone())
src.remove();


//reshow items:
src = $("select[name='ab'] option:eq(0)");
tar = $("select[name='aa']")

tar.prepend(src.clone())
src.remove(); 

Upvotes: 7

gion_13
gion_13

Reputation: 41533

you could disable the ones that you don't want to be able to be selected or you could alter their css display like :

$('select[name="aa"] option').not(':first').css('display','none');

if you want to automatically set a "default" value and do not let anyone change it, you could set the value of the first one and then disable the whole select element so that nobody changes it:

$('select[name="aa"]')
    // set the value of the first option
    .val($('select[name="aa"] option:first').val())
    // disable the select element so that no one can alter it's value
    .attr('disabled','disabled');

Upvotes: 1

SpliFF
SpliFF

Reputation: 39014

what? you mean choose the default option? Try using the selected attribute on the a option

<option selected>a</option>

or to make an option unselectable:

<option disabled>a</option>

Upvotes: 1

bruno
bruno

Reputation: 1841

you can do this:

$("select[name='aa']").val($("select[name='aa'] option:first").val());

Upvotes: 1

Related Questions