Tuesday, April 28, 2009

[jQuery] Re: Simple next/prev controls for <select>

On Tue, Apr 28, 2009 at 1:56 PM, René <renefournier@gmail.com> wrote:
>
> Assuming:
>
> <select id="selector">
> <option value="0" selected="selected">Both</option>
> <option value="1">Red</option>
> <option value="2">Blue</option>
> <option value="3">Green</option>
> </select>
>
> <a id="prev">Prev</a>
> <a id="next">Next</a>
>
> Just wondering if someone has figured a simple jQuery function for
> moving through the a select list (using the above type of controls).
> The idea is that the Prev anchor would disappear if the first option
> is selected, and that the Next ancor would disappear if/when the last
> option is selected.

Well, I don't know if this is "simple" per se... but here's what i got:

<script src="jquery-1.3.2.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
$('#prev,#next').click(function() {
var selector= $('#selector')[0];
var kids = $('#selector').children();

$('#prev,#next').css('visibility','visible');

if (this.id == "prev") {
selector.selectedIndex--;
if (selector.selectedIndex == 0) $('#prev').css('visibility','hidden');
} else {
selector.selectedIndex++;
if (selector.selectedIndex == kids.length-1)
$('#next').css('visibility','hidden');
}
});
});
</script>

<select id="selector">
<option value="0" selected="selected">Both</option>
<option value="1">Red</option>
<option value="2">Blue</option>
<option value="3">Green</option>
</select>

<a id="prev">Prev</a>
<a id="next">Next</a>

That's without manipulating your markup at all. The only thing that
would need attention is that the "Prev" anchor displays when the page
loads.

FWIW, I could have gone with hide() and show() instead of
.css('visibililty', 'hidden') and .css('visibility','visible').
Except hide() and show() are effectively display:none; and
display:block;, both of which remove the elements from the page flow.
Thought it was a little hinky for the 'anchors' to move.

how you finalize it is up to you, but hopefully this gets you a decent
head start.


--
I have failed as much as I have succeeded. But I love my life. I love
my wife. And I wish you my kind of success.

No comments: