Generating a random confirmation code with function()

PennController for IBEX Forums Support Generating a random confirmation code with function()

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #4230
    sarahlee
    Participant

    Hi Jeremy,

    I am trying to generate and display a random 8-digit code to provide as experiment codes for MTurkers.

    I’ve been trying with function(), but I haven’t been able to print the output of the function. The code below didn’t work.

    PennController(
        newFunction("randomString", function() {
        var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
        var string_length = 8;
        var randomstring = '';
        for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
        }
        document.randform.randomfield.value = randomstring;
        })
        ,
        newText("code", getFunction("randomString")
            .call())
            .print()
        );

    Do you have any suggestions?
    Any ideas/suggestions that would help provide a random code would be much appreciated.

    Thanks,
    Sarah

    #4231
    Jeremy
    Keymaster

    Hi Sarah,

    You’re almost there, but unfortunately you can’t refer to other PennController elements in a new* statement. And since you probably want to log the random code as well, I would store it in a Var element (whose .set command can also run javascript code):

    let alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; 
    
    PennController(
        newVar("ID", "")
            .settings.global()
            .set(v =>[...Array(8)].reduce(a=>a+alphanum.charAt(Math.floor(Math.random()*alphanum.length)),''))
        ,
        newText("code", "")
            .settings.text( getVar("ID") ) 
            .print()
    )
    .log("code", getVar("ID"))

    I made the ID var global so you can add its value at the end of your results lines using .log.

    NB: I reused your code but of course the trial defined here will be fully executed (and done) in an instant unless you add a wait command on an element of an appropriate type.

    Jeremy

    #4232
    sarahlee
    Participant

    This works! Thanks so much for the help!

    Sarah

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.