This article describes how to create a custom QScript in Q via the built-in QScript editor.
Requirements
- The Colas.sav file which we will use for this article.
Method - How to write your own QScript
Step 1: Plan
The first step is to work out whether a QScript is appropriate for the task you want to perform. In general, the benefit of a QScript is that it can replace a series of repetitive tasks, especially when this process will be repeated. Ask yourself, is there already a similar script or example code that I can use or modify? If you are unsure of this approach, please contact Support at support@q-researchsoftware.com.
When working out whether a custom QScript is appropriate, outline what you need to do. Some questions to consider:
- Is the QScript intended to be used again?
- How flexible does this script need to be?
- Is it for a specific scenario only or does it need to be applied to different situations?
- Could a user potentially apply it to the wrong type of data or output?
- Is it possible to provide user prompts for all necessary options?
Example:
Below we have a data set that displays the question text shown in our survey but not the question number, i.e. Q1, Q2 etc.
We could manually append these labels but this could also be automated via QScript. Let's look at a short example of a QScript that updates the Question Name to include the variable Name so we get d1 - Age, for example, instead of just Age.
Now, what if we also want to allow the user to control which variable sets we apply this to? What about when we only want part of the prefix from the variable name to be included? The below will take us through the various steps to consider when creating a custom QScript using this example as a guide.
Step 2: Open the QScript Editor
From the toolbar, go to Automate > Browse Online Library > Open QScript (Macro) Editor.
Step 3: Add the relevant JavaScript library
If you intend to use functions from some of our online libraries then this needs to be referenced upfront using the includeWeb
function and the name of the library:
includeWeb("QScript Selection Functions");
See Online JavaScript Libraries for details on the various libraries and functions available for QScripts. Here, we will include the QScript Selection Functions library as we will use a selection function that requires this.
Step 4: Declare your key variables
If you are working with data sets, variables, tables, or other objects, you will need to first declare these before writing the bulk of your code. This is also a good way to work out what you potentially will need to write in your code.
In our example, we will need to loop through each variable set so the key variables to declare in this case are the questions, the data file they come from, and the number of iterations for our loop:
var questions = project.dataFiles[0].questions; // get all questions
var n_questions = questions.length; // number of questions
questions
stores allquestion
objects in our data set.n_questions
useslength
to find the number of items inquestions
to loop through.
See JavaScript Fundamentals and How to Work with Variables via QScript.
Step 5: Add selection options and input controls
When a QScript is going to be used repeatedly and needs to be flexible, selection options and input controls can offer an easy way to allow the user to select the options they want to apply.
Options include:
- Current selections
- Variable and question selections
- Numeric and text fields
- Combo and list boxes
Generally, the workflow would be to declare the variable sets first and then populate a user control with these to choose from. In our example, however, we have decided we don't wish simply to run the script on all questions, but also allow users to run this only on specific variable sets as well.
In this case, we can replace the below...
var questions = project.dataFiles[0].questions; // get all questions
...with the following which uses the getAllUserSelections()
function from the QScript Selection Functions library:
var user_selections = getAllUserSelections();
var questions = user_selections.selected_questions;
- The
selected_questions
property returns all thequestion
objects within the selection. The data set does not need to be declared as this is already taken into account with the user selection. Note, the equivalent for thevariable
object isselected_variables
. - Note, this will run on the items selected within your Variables and Questions tab only.
See How to Create User Input Prompts in QScripts.
Step 6: Write your main script
The main part of your code should appear here. In our example, this will include the looping through the questions in your data set and modifying them.
Here, we place the code that does the actual work of renaming the question name:
// loop through each question
for (var i = 0; i < n_questions; i++) {
var q_name = questions[i].name; // get question name
var var_name = questions[i].variables[0].name; // name of first variable in question
questions[i].name = var_name + " - " + q_name; // set question name
}
- We use a
for..loop
that loops through every question and returns their Name asq_name
and the first variable name asvar_name
. questions[i].name
then sets the question name by adding the variable name to the existing name.
See How to Work with JavaScript Arrays and Loops, How to Modify Variables and Value Attributes via QScript, and How to Create Custom Variables via QScript.
For other worked examples, see also How to Create a Banner via QScript, How to Add Folders and Text Outputs via QScript, How to Create Tables and R Calculations via QScript, How to Create a Chart via QScript, and How to Modify Tables via QScript.
Step 7: Add validations and messages
Validations can be performed to check, among others, whether:
- The input selections match the requirements of the script.
- Any user prompts contain valid inputs.
- The variable set structure of the input questions requires different code or is not appropriate.
Messages can similarly be used to:
- Notify users if there is an issue with their inputs.
- Notify users that the script has finished.
For example, we may wish to deal with situations where the variable set is a grid-style question and the first variable name contains extra characters that we don't wish to include, such as "_1" in Q5_1. This validation can be as complex and flexible as you want, but here we will simply restrict the variable name to 3 characters using substring
and replace "_" with a blank:
var_name = var_name.substring(0,3).replace("_","");
This line needs to be added directly before the last row within the loop which re-sets the variable name.
As an aid to the user, we can also add a log message at the end to say when the script has finished:
log("Your question labels have now been updated");
See How to Create Diagnostic Messages and Perform Validations via QScript and How to Manipulate Strings Using JavaScript.
Step 8: Write any custom functions (optional)
Custom functions can help with simplifying the bulk of your code, especially when performed in multiple places. Functions can be added anywhere in the code, but for readability, it is often easier to place these at the bottom so the main part of the code is more accessible.
We will now update our loop code so you can see it as a custom function:
for (var i = 0; i < n_questions; i++) {
addVariableNameToQuestionName(questions[i]);
}
function addVariableNameToQuestionName(question) {
var q_name = question.name; // get question name
var var_name = question.variables[0].name; // name of first variable in question
var_name = var_name.substring(0,3).replace("_",""); // tidy variable name
question.name = var_name + " - " + q_name; // set question name
}
- Our function is called
addVariableNameToQuestionName
which takes only a single argument calledquestion
. - The main internal loop code is now placed within this function and remains predominantly the same. The only change is that
questions[i]
is replaced withquestion
due to this code taking place within the function itself rather than the loop, so it instead takes its input from the function argument. - The contents of the original loop are now simply the function name and the
questions[i]
input.
Step 9: Check your code and save
- Press the Play button to check for code errors which, if any, will appear on screen.
- Check that the script has worked.
- If there are no issues, press the Save icon and enter a name for the file so it can then be saved to your computer.
- If you don't get what you're after, continue amending your script via the QScript Editor.
Note, once this screen is closed, you can still go back to it via Automate > Browse Online Library > Open QScript (Macro) Editor > Open folder icon, and select your script.
Here is the updated JavaScript in full:
includeWeb("QScript Selection Functions"); // load one of our libraries
var user_selections = getAllUserSelections(); // identify the selected questions
var questions = user_selections.selected_questions; // get all the questions
var n_questions = questions.length; // number of questions
for (var i = 0; i < n_questions; i++) { // loop through the questions
addVariableNameToQuestionName(questions[i]); // run the custom function below
}
log("Your question labels have now been updated"); // print a message once finished
function addVariableNameToQuestionName(question) { // a custom function
var q_name = question.name; // get question name
var var_name = question.variables[0].name; // name of first variable in question
var_name = var_name.substring(0,3).replace("_",""); // tidy variable name
question.name = var_name + " - " + q_name; // set question name
}
Resources: Learning JavaScript
How to Work with Conditional JavaScript Formulas
How to Manipulate Strings Using JavaScript
How to Work with JavaScript Arrays and Loops
How to Troubleshoot JavaScript Code in Q
Series: Learning How to Write Your Own QScripts
1. How to Work with Variables via QScript
2. How to Create a Banner via QScript
3. How to Create User Input Prompts in QScripts
4. How to Create Diagnostic Messages and Perform Validations via QScript
5. How to Modify Variables and Value Attributes via QScript
6. How to Create Custom Variables via QScript
7. How to Add Folders and Text Outputs via QScript
8. How to Create Tables and R Calculations via QScript
9. How to Create a Chart via QScript
10. How to Modify Tables via QScript
Next
How to Work with Variables via QScript