I would like to add a thousands separator to a numeric field as people type in an answer.
To be safe, this example uses a free format question that adds commas to input and saves two answers: one with commas and one without commas.
To begin, create a free format question and add two variables: a text variable and a numeric hidden variable. (Note: Numeric fields are limited to 999999999 (nine nines), so if more digits are need then make the hidden variable text instead of numeric) Place the required HTML on the page for the variables to display and save correctly. An easy way to make sure the HTML is correct is to make SSI Web to it. Click the pencil icon next to the HTML box on the Variables/Question HTML tab of the free format question to bring up the text editor. Click the hammer and wrench icon at the top of the page and select the variable you want to insert.
Explanation of code
- Contains a jQuery anonymous function that run the code once all of the content on the page has been loaded and the document is ready for further interaction.
textbox. jQuery will use this to manipulate the text typed into the input box. In the above example the name of the free format question is
ThousandSeparatorand the name of the text free format variable is
ThousandSeperator_commas. This name will need to change to whatever free format variable name the current study is using.
- Does the same thing as Line 3, but for the free format hidden variable.
#ThousandSeperator_numwill also need to change to match whatever is in the current study (the format is:
- Will make sure that lines 6 through 11 are run every time a number is typed into the text input field.
- Grabs the current value of the text input box and saves it to a variable called
- Sets up a regular expression that will find commas in the number pulled from the text input box.
- Removes any commas currently in the number. Without doing this 1,000 becomes 1,0,000 instead of 10,000 when a fourth zero is entered.
- Saves the number to the hidden variable.
- Adds commas back in to the number.
- Puts the number, containing thousands separators in the correct places, back in the text input box.
- Ends the function started in line 5.
- Ends the function started in line 2.
- Blank line for readability.
- This is the function that inserts commas into a number.
Note: If only a number with commas needs to be stored in respondent data than this can be done with just a text question instead of a free format question. If that is the case then
textbox will be equal to the name of the question, and lines 4, 7, 8, and 9 (dealing with the hidden free format variable) can be deleted.