Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery block <select> to first option

Tags:

jquery

select

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

like image 609
haltman Avatar asked Dec 28 '22 01:12

haltman


2 Answers

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(); 
like image 153
Caspar Kleijne Avatar answered Jan 11 '23 05:01

Caspar Kleijne


you can do this:

$("select[name='aa']").val($("select[name='aa'] option:first").val());
like image 23
bruno Avatar answered Jan 11 '23 04:01

bruno