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>

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

4 Comments

The code seems not work :( I added it before the </script> - tag.
I updated it. You must place this code after your selectable stuff and before the closing ready listener callback.
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.
Please check your random number. It delivers numbers from 1 to 8. Please review it here: link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.