tags:

views:

46

answers:

2

Im using the following function to hide a series of forms on a page:

$('.ask').toggle(function() {
      $(this).text('-').next('.addtitle').slideDown('fast');
    }, function() {
      $(this).text('+').next('.addtitle').slideUp('fast');
});

There can be anything from 0 to 5 forms on the page all with the class .ask

What I want to be able to do is to select one form NOT to hide, so the jQuery needs to hide all put one of the forms on the page randomly.

How can I achieve this?

A: 

You can just hide one initially at random, like this:

$('.ask').toggle(function() {
  $(this).text('-').next('.addtitle').slideDown('fast');
}, function() {
  $(this).text('+').next('.addtitle').slideUp('fast');
});
var articles = $('.addtitle');
articles .hide().eq(Math.random() * articles.length).prev('.ask').click();​​​​​​​​

This is based on your previous question's markup, you can view a quick demo here :)

Nick Craver
I need to keep the toggle action and the $(this).text('+') or ('-')
danit
@danit -I noticed your question and previous markup weren't quite in sync, I updated it to use the same markup in your previous question, try the demo, it should leave the + and - in the right state.
Nick Craver
Superb, thanks. I've noticed that when refreshing the page it will work - then refresh again and all are hidden.
danit
@danit - there was an extra -1 in there initially, try the current answer, should work or you :)
Nick Craver
Thanks for your help. Also is it possible to just make the first occurance on the page expanded rather than random?
danit
@danit - Yup, just replace `.eq(Math.random() * articles.length)` with `.eq(0)` or `.first()` :)
Nick Craver
A: 

You could use the .not() function to exclude some element at a given random index:

var indexToExclude = Math.floor(Math.random() * $('.ask').length);
$('.ask').not(':eq(' + indexToExclude + ')').toggle(function() {
    $(this).text('-').next('.addtitle').slideDown('fast');
}, function() {
    $(this).text('+').next('.addtitle').slideUp('fast');
});
Darin Dimitrov
You'd still want to bind the `toggle` across the board, he just wants to show one of the `.addtitle`, which is where the actual forms are are, and leave the `.toggle()` in the right state of course.
Nick Craver