0 votes
by (220 points)
Hello!

In my Twine project, I am giving the user a box to input text. I would like to do a number of things, if possible:

1. Have twine count the words the user inputs

2. Show this wordcount to the user (live, if possible?)

3. Trigger an action once a certain wordcount is reached

4. Assign a value to this user-inputted text (so I can make the project recall it later)

Are any/all of these things possible to do?

I tried searching the forums for wordcount related keywords but didn't dig up anything.

2 Answers

+1 vote
by (63.1k points)
selected by
 
Best answer

Try something like this:

<<textbox '$input' '' autofocus>>
<span id='input-report'>0</span>

<<script>>
postdisplay['read-input'] = function (t) {
    $('#textbox-input').on('keyup', function () {
        // get word count from textbox
        var lt = $(this).val().match(/\S+/g).length;
		
        if (lt <= 10) {
            // update input count
            $('#input-report').empty().append(lt);
        } else {
            // word limit reached
            $(this).attr('readonly', true); // maybe?
            $('#input-report').css('color', 'red');
            UI.alert('Word count limit reached.');
        }
		
    });
};
<</script>>

Obviously, you'll want to make edits where appropriate, based on what you're trying to do.

by (160 points)
That's clever!
by (220 points)
Thanks so much!
+1 vote
by (160 points)

The first and fourth ones are easy enough.

<<textbox $input>>
<<set $wordCount to $input.split(" ").length>>

$input will continue to hold the string. $wordCount will hold the number of words. The split function in JS takes a string of characters and splits them up into an array based on whatever is in the parentheses. The length property holds the number of elements in the array, so that gives us the word count.

I'm not sure how to approach 2 or 3, but it would definitely be something on the side in JS.

by (63.1k points)

You need to quote the variable name to pass it to the text box, and I'm pretty sure you can't omit the 'default text' option, meaning you at least have to give the text box macro an empty string.

<<textbox '$input' ''>>

 

...