0

How do I define jQuery selectables selected by random number? By now the selectables become selected if I click on each of them. But I would like to get these auto-selected randomly.

My code looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">

<style type="text/css">
#selectable .ui-selecting { background: #FECA40; }
#selectable .ui-selected { background: #F39814; color: white; }
#selectable { list-style-type: none; margin: 0; padding: 0; width: 350px;}
#selectable li { margin: 3px; padding: 1px; float: left; width: 100px; height: 80px; font-size: 4em; text-align: center; line-height: 80px; cursor: pointer; cursor: hand; }
</style>

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

<script type="text/javascript">
 $(function() {
     $( "#selectable" ).selectable({
     stop: function() {
         var result = $( "#select-result" ).empty();
         $( ".ui-selected", this ).each(function() {
             var index = $( "#selectable li" ).index( this );
             result.append( " #" + ( index + 1 ) );
        });
        }
    });
});
</script>
</head>
<body>

<ol id="selectable">
    <?php
        for($i=1;$i<=9;$i++) {
            echo "<li id=\"field_$i\" class=\"ui-state-default\">$i</li>";
        }
    ?>
</ol>
</body>
</html>
user3524628
  • 137
  • 1
  • 3
  • 14

1 Answers1

0
<script>

  $(function() { // Start 'ready' listener

    $( "#selectable" ).selectable({
      //... your stuff
    });

    // Select a random <li> element
    var rand = Math.floor(Math.random() * 9) + 1; // return 1 <= rand <= 9
    $("#field_" + rand).click();

  }); // End 'ready' listener

</script>

Here is a simple example of how it works : http://jsfiddle.net/Oliboy50/VLetY/

Oliboy50
  • 2,661
  • 3
  • 27
  • 36
  • The code seems not work :( I added it before the - tag. – user3524628 Jul 28 '14 at 09:39
  • I updated it. You must place this code after your `selectable` stuff and before the closing `ready listener callback`. – Oliboy50 Jul 28 '14 at 09:51
  • Well it alerts a random field but my question was how to mark a selectable field automatically as selected. No field changes its background color when the click takes place. – user3524628 Jul 28 '14 at 10:09
  • Please check your random number. It delivers numbers from 1 to 8. Please review it here: [link](http://stackoverflow.com/questions/3594177/random-number-between-10-and-10-in-javascript) – user3524628 Jul 28 '14 at 10:12