Forum Discussion

RichardMulcahy's avatar
RichardMulcahy
Community Member
4 hours ago

Any JavaScript Experts Out There?

I found this sample code on the web, but it's not working for me. I'm trying to limit the number of characters a user can enter (for example 5), and if they exceed then I show a layer with an error msg. Here is the code and my SL file. I'm sure it's something simple.

 

var textFields = document.querySelectorAll(‘input[type=”text”]’);
var maxChars = [8, 12];
var player = GetPlayer();

textFields.forEach(function(textField, index) {
    textField.addEventListener(“input”, function() {
        var maxLength = maxChars[index];
        if (textField.value.length > maxLength) {
            textField.value = textField.value.slice(0, maxLength);

            player.SetVar(“ShowLayer”, true);
        } else {

            player.SetVar(“ShowLayer”, false);
        }
    });
});

  • A few things going on here. The first is with the quote characters those are throwing an error. Unless it's in a code field, stuff off the internet can frequently use the wrong characters. JavaScript is literal and will completely bomb if a character is out of place. 

    An easy way to check for errors is to preview, then use the Inspect feature. Scroll to the top of the DevTools window and if there's an error in user.js, it's a syntax problem. However, even after resolving that problem, the script doesn't do what you'd hope it would do. I don't think the method the site where the script came from works, at least not with the latest version of SL. 

    Logical field connections appear abstracted. There's the visual representation of the text box and another representation of the text block behind that. There is likely some accessibility reason for this. Hard to tell. I added a console log to show the text fields on the screen with just the two text blocks below.

    There is a timing issue happening somewhere in the stack. Operating off of the variable alone in JS won't help because the value isn't committed until after the text box is left. Your best bet will likely be using a webobject that contains all of your textbox limits and interactions. You can link this webobject to your SL variables using Javascript.