Open random record from model via button

Hi team! 

I’m currently trying to implement a feature which opens a different random record from the model on each button click.

This is as far as I got with my snippet:

var Model = skuid.model.getModel('Images'); <br>var rows = Model.data.length;<br>var randomNum = Math.floor(Math.random() * rows) + 1;<br>var Link = skuid.model.getModel('Images').data.row[randomNum].Link__c; window.open(Link, '_blank');


The “Link__c” field contains a valid URL of an image. What I am struggling with are 2 things:

1) Correct syntax to call a specific row in the model
2) Correct implementation of producing a random number, and then passing this on to retrieve the corresponding row


My coding and Javascript skills are pretty much limited to copy and paste, so I appreciate simple language whenever possible :slight_smile:


Thank you in advance!

Robin


You are very close. Just two things:

a. You should not add 1 to the random number because Javascript arrays have a zero based index.
b. To retrieve the link write “var Link = Model.data[randomNum].Link__c;” using the Model variable and without the ‘.row’

Menachem, 

Thank you so much for the explanation and description! I just edited the script and it works :slight_smile:

Phenomenal result, appreciate your help with this!

The community delivers again. Here is the modified script:

var params = arguments[0], $ = skuid.$;<br>var Model = skuid.model.getModel('Images');&nbsp;<br>var rows = Model.data.length;<br>var randomNum = Math.floor(Math.random() * rows);<br>var Link = Model.data[randomNum].Link__c; &nbsp;<br>window.open(Link, '_blank');

Glad this worked for you.  Interesting use case…