Actions

Esempi di sondaggi con ExpressionScript

From LimeSurvey Manual

Revision as of 13:07, 2 October 2020 by Ritapas (talk | contribs) (Created page with "{{Nota|A livello di sottodomanda, introduciamo anche la variabile "this" per semplificare la convalida di ogni cella in un array senza dover conoscere il nome della variabile....")


Introduzione

il modo migliore per imparare ad usare ExpressionScript è provare esempi funzionanti e modificarli secondo le proprie esigenze.

Nel testo seguente sono disponibili alcuni sondaggi di esempi per valutare come si può usare EM per migliorare i propri sondaggi. Questi sondaggi sono anche disponibili nella directory /docs/demosurvey della distribuzione.


Rilevanza, Adattamento ed Equazioni

Panoramica

L'esempio seguente calcola l'IMC (Indice di Massa Corporea, in inglese Body Mass Index) del partecipante. L'esempio mostra diverse caratteristiche, illustrate più avanti.

Dimostrazione delle caratteristiche dell'EM

  1. Rilevanza - supporto per logica condizionale "potente";
  2. Piping / Tailoring - offre la possibilità di concatenare o adattare le risposte e i metadati delle domande;
  3. Adattamento Dinamico - report che cambiano sulla pagina stesas mentre si digitano le risposte.
  4. Micro-Tailoring - adattamento condizionale all'interno di frasi e report con l'utilizzo di istruzioni if()
  5. Equazioni - un nuovo tipo di domanda che consente l'esecuzione di calcoli, anche nascosti, e la conservazione dei risultati sul database
  6. Convalida dondizionale - criteri di convalida, come ad esempio il valore minimo accettabile, possono essere ora condizionali, vale a dire basati su equazioni.


Screenshot

Questo esempio calcola l'Indice di Massa Corporea, un indice basato sul peso e l'altezza che determina se si è sottopeso, normopeso, sovrappeso o obesi. All'inizio, sono mostrate solo le quattro domande obbligatorie.



Dopo aver inserito le informazioni (ed aver scelto se si desidera utilizzare unità metriche o meno), è mostrato un report personalizzato che riassume i dati inseriti e mostra l'indicatore dello stato di peso forma.



Ecco un altro esempio, che utilizza unità non metriche per mostrare come i risultati cambiano dinamicamente:



Sono state inserite domande nascoste di tipo Equazione per convertire i dati nel sistema metrico, quando appropriato. In queste domande sono conservati altezza e peso in unità metriche, che confluiscono nella base dati, con l'indice IMC e lo stato di peso forma, senza che si debba creare codice JavaScript personalizzato.

Negli esempi successivi è mostrato come mostrare funzioni, matematiche o d'altro tipo, all'interno di report personalizzati. Prima dell'inserimento di dati, la pagina appare in questo modo. Grazie alla logica condizionale, se non sono presenti dati numerici le celle restano vuote invece di mostrare "NaN" o "Divide by Zero".



Dopo che sono stati inseriti i numeri, il report della pagina è modificato e mostra il calcolo eseguito e il suo risultato.



Nel sondaggio di esempio sono presenti molti altri esempi. Ad esempio, nella schermata seguente è mostrata una delle tante maniere nelle quali è possibile compilare la pagina Dynamic Relevance. Come illustrato nelle note, è possibile provare a inserite diverse età e, in particolare, all'inserimento di combinazioni incompatibili di risposte sono mostrati messaggi divertenti. Si noti anche che se si dichiara di avere più di un figlio, il messaggio dirà "I hope you enjoy playing with your X children" ("spero che ti diverta a giocare con i tuoi X bambini"), piuttosto che declinare la frase al singolare. Con questo si mostra come si possono personalizzare singole frasi per adattarle al genere e/o al numero dei sostantivi utilizzati, come anche si possono anche coniugare facilmente verbi.



Download

Per scaricare il sondaggio di esempio, utilizzare il link seguente: LS3_em_tailoring.zip.

Sample Census

Introduzione

Questo è un esempio di censimento nel quale si chiede quante persone costituiscono il nucleo familiare.

Mostra in che modo è possibile utilizzare la rilevanza a livello di gruppo per implementare facilmente la ripetizione ciclica di domande ("loop"). Dopo aver creato il gruppo per "Person 1", questo è stato esportato. Avendo utilizzato nomi di variabile qcode del tipo p1_name, si è potuto utilizzare un editor di testo per modificare velocemente e re-importare i gruppi più volte: sono stati sufficienti 10 secondi per modificare e re-importare ogni nuovo gruppo mantenendo nomi unici per le variabili e logica corretta a livello di gruppo.

Sarebbe stato possibile utilizzare anche l'opzione copia domanda ma l'opzione mostrata è più rapida.

Si vede anche come evitare che il messaggio di Fine compilazione appaia solo quando il sondaggio è effettivamente terminato (vale a dire, quando tutti i gruppi obbligatori sono completati).


Dimostrazione delle caratteristiche di EM

  1. Rilevanza a livello di gruppi - I gruppi successivi ("Person 1-5") sono mostrati solo fino al numero di conviventi specificati;
  2. Adattamento - Il report finale riassume i dati demografici di ciascun convivente;
  3. Visualizzazione progressiva delle domande - Sia in gruppo che in modalità pagina singola, le domande successive sono mostrate mano a mano che le precedenti ricevono una risposta.


Screenshot

Il sondaggio produce un report dinamico nel quale sono mostrati i dati demografici dello specifico numero di conviventi:



Se il sondaggio è mostrato una domanda alla volta, si vede che l'indice si adatta alle domande. Dal momento che l'utente ha scritto che la persona è una donna, la domanda (in inglese) è declinata al femminile. E visto che è stato inserito il suo nome, "Mary", la domanda successiva chiede "How old is Mary?" ("Quanti anni ha Mary?").



Download

Usare il link seguente per scaricare il sondaggio di esempio: LS3_group_relevance.zip.


Filtri concatenati per Array

Panoramica

Il sondaggio seguente si basa su un originale gentilmente concesso da Joy Lane Research, LLC.


Screenshot

Nelle immagini seguenti, notare che.

  • Q2 mostra solo i prodotti selezionati (con array_filter) in Q01
  • Q02 mostra anche "Another product", ovvero il testo inserito nel campo "Other electronic" di Q01
  • Q04 mostra solo prodotti in Q02 che sono stati selezionati (filtraggio concatenato)
  • Q05 mostra solo prodotti in Q02 che NON sono stati selezioati in Q02 (filtraggio concatenato che utilizza array_filter_exclude)




Download

Utilizzare il seguente link per scaricare l'esempio precedente:LS2_cascading_array_filter sondaggio di esempio.


Adattamento/Piping utilizzando tutti i tipi di domanda e attributi

Panoramica

Se siete confusi su come nominare le vostre variabili (SGQA o Qcode), non siete soli. Anche se la documentazione descrive come comporre nomi di variabile Qcode, niente è meglio che osservare una demo funzionante. Il sondaggio seguente mostra come accedere ad attributi di domanda e risposte utilizzando ExpressionScript.


Per questo esempio, si consiglia di disattivare l'editor HTML integrato (o di convertirlo in modalità popup) durante la modifica di questo sondaggio. L'editor HTML può impiegare un minuto o più per eseguire il rendering dei rapporti HTML di grandi dimensioni in modalità di modifica.


Contenuto

  • Esempi per ogni tipo di domanda
  • Sono inclusi tutti i tipi di domande che utilizzano "altro", in modo da mostrare come ciò influisca sulla denominazione delle variabili
  • Valori predefiniti per tutti i tipi di domanda che accettano valori predefiniti
  • Adattamento - Rapporti in pagina e fuori pagina che mostrano tutti i 16 suffissi disponibilil per EM.
  • Questi report mostrano tutti i dati attualmente inseriti (quindi mostrano come generare i propri rapporti stampabili per gli utenti al posto della stampa diretta della schermata delle risposte)
  • Qcode corretto e denominazione SGQA di tutte le variabili


Screenshot

Questo è un sondaggio enorme, quindi abbiamo scelto di non includere schermate. Consigliamo piuttosto di scaricarlo e giocarci un po'.


Download

Fare clic sul collegamento seguente per scaricare il sondaggio: LS3_EM_question_attributes.lss

Validazione tradizionale, rivisitata

Panoramica

Dimostrazione di tutti i tipi di convalida che fanno uso di espressioni e di come esse influiscono su ciascuno dei tipi di domanda che supportano la convalida. In molti casi, i suggerimenti di convalida sono inizialmente nascosti e vengono visualizzati solo se una domanda non soddisfa i criteri di convalida (scomparendo, pertanto, una volta che la domanda superi i criteri di convalida).


Dimostrazione dei tipi di convalida

  1. min_num_value_n - valore minimo per una risposta#max_num_value_n - valore massimo per una risposta
  2. min_answers - numero minimo di risposte obbligatorie
  3. max_answers - numero massimo di risposte consentite
  4. multiflexible_min - numero minimo consentito per una risposta (per il tipo di domanda con numeri multiflexi)
  5. multiflexible_max - valore massimo consentito per una risposta (per il tipo di domanda con numeri multiflexi)
  6. min_num_value - valore minimo consentito per la somma di tutte le risposte alla domanda
  7. max_num_value - valore massimo consentito per la somma di tutte le risposte alla domanda
  8. equals_num_value - la somma di tutte le risposte alla domanda deve essere pari a questo valore
  9. validation - espressione regolare di convalida per la domanda - può essere applicata a singole celle


Screenshot

Utilizzando nuovi stili CSS, ogni tipo di convalida mostra un suggerimento separato. Se vengono visualizzati, possono essere nascosti tramite l'opzione hide_tip. L'opzione predefinita è mostrarli con un carattere rosso se la domanda non soddisfa i criteri di convalida e verde se li supera:



Un utente non può inviare una pagina con errori di convalida. Verrà immediatamente avvertito se ha inserito informazioni errate:



La convalida può essere applicata a singole celle all'interno di un array, come in questo esempio, in cui le convalide delle espressioni regolari assicurano che ogni voce sia un numero di telefono statunitense formattato correttamente, incluso il prefisso.



Download

Per scaricare l'esempio precedente, fare clic sul seguente collegamento: LS3_Validation_tests.zip.


Equazioni di convalida

Panoramica

A volte è necessaria una convalida personalizzata che non può essere ottenuta utilizzando i tradizionali criteri minino/massimo. Per questo, sarà necessario utilizzare le opzioni em_validation_q e em_validation_sq, che consentono di costruire equazioni di convalida complesse rispettivamente a livello di domanda e sottodomanda.


Template:Nota


EM Features Demonstrated

  1. em_validation_q - this is an equation that determines whether the whole question is valid
  2. em_validation_q_tip - this is the message to show if the question fails em_validation_q criteria
  3. em_validation_sq - this is the equation that determines whether each subquestion (array cell) is valid
  4. em_validation_sq_tip - this is the message to show if any of the subquestions is invalid.

In general, when em_validation_sq is used, if any cell is invalid, the background color for that cell turns red to indicate that there is an error.


Screenshots


This question ensures that you enter the ages of your children in descending order by applying this validation equation:

q1_sq1 >= q1_sq2 && q1_sq2 >= q1_sq3 && q1_sq3 >= q1_sq4





In the below example, the validation ensures that no more than 3 questions are answered on any given row by applying this validation equation:

(sum(Test_A_1, Test_A_2, Test_A_3, Test_A_4, Test_A_5) <= 3) && (sum(Test_B_1, Test_B_2, Test_B_3, Test_B_4, Test_B_5) <= 3) && (sum(Test_C_1, Test_C_2, Test_C_3, Test_C_4, Test_C_5) <= 3)

You can also write this as follows, LimeSurvey automatically converting it at run-time to the above-listed expression.

(sum(self.sq_A) <= 3) && (sum(self.sq_B) <= 3) && (sum(self.sq_C) <= 3)



Download

To download the survey sample used in the above examples, click on the following link: ls2_test_em_sq_validation.lss.


Subquestion relevance

Overview

This shows how array_filter and validation criteria can interact. For validations that apply to sums, only relevant (visible) values are considered.


EM Features Demonstrated

  1. array_filter
  2. array_filter_exclude
  3. min_num_value
  4. max_num_value
  5. equals_num_value

It also shows dynamic reporting of the numbers of questions answered in the core questions.


Screenshots

Changing the number of visible rows dynamically changes the sum. Marking a subquestion as being irrelevant doesn't clear its value. Rather, if it is irrelevant, its values don't contribute to any equation.



Note what happens when we check the "Fifth subquestion" for the first question "Which rows should appear below". Note that the sum for the second "Enter some numbers" question is now 5. Even though subquestion 5 for that question still has the value 14 (e.g., if you un-check the fifth subquestion, you will see the value of 14 again), that value does not contribute to the sum since it is currently irrelevant. All irrelevant data is cleared (NULLed in the database) on submit, but it stays available on the page in case users want or need to change their minds about answers.



Download

To download our example, click here: ls2_subquestion_relevance.lss.


Using Comma as Radix Separator (Decimal Point)

Overview

The ExpressionScript ensures that only valid numbers can be entered into numeric fields. If you enter an invalid number, you will be warned that something is wrong (e.g., in the case of the fruity theme, the whole question is "red-ed").

Note that the numeric values are always converted to using a period as the radix separator within the database. In this way, the statistical analyses will work appropriately.

To change the radix separator, access the Text elements options located under the Settings tab, and look for the decimal mark functionality.


For more information on what a radix separator is, click [https://en.wikipedia.org/wiki/Radix_point


Question Types Using Radix Separator

  1. Numerical input [N]
  2. Multiple numerical input [K]
  3. Array (Numbers) [:]
  4. Array (Texts) [;], when using the numbers_only attribute
  5. List (radio) [L], when using the other_numbers_only attribute
  6. Short free text [S], when using the numbers_only attribute
  7. Multiple short text [Q], when using the numbers_only attribute
  8. Multiple choice [M], when using the other_numbers_only attribute
  9. Multiple choice with comments [P], when using the other_numbers_only attribute


Screenshots

You may note in the below screenshots that comma can be used as a radix separator.



Download

To download the above example, click on the following link: ls2_comma_as_radix_separator.lss.


Randomization Groups

Overview

This survey demonstrates how to make use of the random_group attribute.

If this attribute is used, each time you start the survey, the question order is randomized. However, once the survey is started, the randomization order remains fixed, even if you change languages.


Screenshots

Let's check together the below example. The first random question on the page will either be Q1 , Q4, or Q7. The second randomized question on the page will either be Q2, Q5, or Q8.



Here is the randomization generated the first time I tested this survey.



A different randomization was generated the second time I tested the survey.



But, when I switched to French (without re-starting the survey), the randomization order remained intact.



Download

To download the above example, click on the following link: Randomization_Group_Test.lss


Randomly Ask One Question Per Group

Overview

This survey shows how you can configure a survey to randomly display one question per group. In it, there are 5 groups of 6 questions each. At the outset, in Group 0, five hidden Equation questions, called ask1-ask5, are populated. Each one has the value of {floor(rand(1,6.9999))} in the question text field, which means that the variables ask1-ask5 will each have a value between 1 and 6. Then, each question in the group has a relevance equation like "ask1==N" where N is the Nth question in the group (so the third question in group 1 has the relevance equation "ask1==3").

This survey works equally well in survey-at-a-time, group-by-group, and question-by-question modes. Since the randomization is set in the first group, and that group is effectively hidden (since all of the ask1-ask5 questions are hidden), the randomization stays the same for the subject; but each different subject will have a distinct randomization.


Features Demonstrated

  1. Equation question type
  2. Randomization functions
  3. Conditional (if) function


Screenshots

This is Group0, which uses the Equation question type to select random values from 1 to 6 for each group (except the last group, which has only 4 questions). Note that the "if()" function first checks whether ask1 has already been set, and if so, uses that value. If the value hasn't been set, then it uses a random value to set the value of ask1.



This Group shows how the variable (ask4) from Group0 is used to control which question is visible within the fourth group.



Download

To download the above survey example, click here: Random questions within a group survey example.


Randomly Ask A Specific Number Of Questions In A Group (a subset of the questions)

  This applies only to all random questions from one group and only if the Group by group or All in one format is used.



Overview

This survey shows how to ask a random subset of questions in a group. For example, show 5 random questions out of 10 questions located within a group.

The survey has one group containing 10 questions. All questions are assigned the same randomization group name. As a result, they will be displayed in a random order on page load. Each question is given a relevance equation that the sum of the "relevanceStatus" of all other questions in the group is less than the number of questions you want to show. Since relevanceStatus is assigned as questions are rendered, this effectively totals the number of preceding questions.

So, in our 5 out of 10 example, the equation for Q1 would be:

sum(Q2.relevanceStatus, Q3.relevanceStatus, Q4.relevanceStatus, Q5.relevanceStatus, Q6.relevanceStatus, Q7.relevanceStatus, Q8.relevanceStatus, Q9.relevanceStatus, Q10.relevanceStatus) LT 5

For Q2, it would be:

sum(Q1.relevanceStatus, Q3.relevanceStatus, Q4.relevanceStatus, Q5.relevanceStatus, Q6.relevanceStatus, Q7.relevanceStatus, Q8.relevanceStatus, Q9.relevanceStatus, Q10.relevanceStatus) LT 5

And so on...


Features Demonstrated

  1. relevanceStatus variable
  2. Randomizing

Download

To download the above example, click on the following link: Random 5 out of 10 survey example.

Rating User-Entered List of Products

Overview

The below example shows how you can ask users to list a set of products that interest them, and then have them rate those products.


ES Features Demonstrated

  1. Tailoring answers - when rating products, the labels come from the comment field of the preceding multiple choice question
  2. Tailoring scales - many advanced questions options, like scale headings, can also be tailored.


Screenshots

This image shows that even though only products 1,3, and 5 were selected, only those 3 are displayed (using the array_filter attribute). Moreover, the row labels in the second question are either the product numbers (if nothing is entered into the comment field) or the contents of the comment fields.



This image shows how the tailored answers are specified:



Here is the Show Logic File for that question, which lets us verify that the conditional logic works as desired (e.g., to see whether there are any syntax errors):



The next image shows a group in which you specify a 5 point rating scale (Options 1-5), the title of the scale, and the products you want to rate. The final question shows that each of the parts of the array question can be tailored:



The next image shows the logic file view of the last question. As you can observe, the subquestions, answers, and scale headers can be tailored.



Download

To download the survey example from above, click on the following link: Rating user-entered list of products survey example.