surveyjs

Using html in question titles in survey.js


We are creating a form with survey.js. However, we will add a checkbox for mandatory choices regarding kvkk and we need to show some text in the title for the explanations to be seen. We also want to add capctha verification.

sample

I tried to write html content for the titles on the survey.js screen but it didn't work


Solution

  • SurveyJS supports formatting of labels and titles through Markdown, however it can be extended to support HTML as well. To acheive that you need to use a library like markdown-it. You will also need to handle the onTextMarkdown event of the Survey. This is documented with a working demo here.

    Here's how to implement this with React:

    import React from "react";
    import { Model } from "survey-core";
    import { Survey } from "survey-react-ui";
    import "survey-core/defaultV2.min.css";
    import "./index.css";
    import { json } from "./json";
    import markdownit from "markdown-it"; // <-- Import the 3rd party library
    
    function SurveyComponent() {
      const survey = new Model(json);
      survey.onComplete.add((sender, options) => {
        console.log(JSON.stringify(sender.data, null, 3));
      });
      // Instantiate `markdown-it`
      const converter = markdownit({
        html: true, // <-- Enable HTML support
      });
      survey.onTextMarkdown.add((_, options) => {
        // Convert Markdown to HTML
        let str = converter.renderInline(options.text);
        options.html = str;
      });
      return <Survey model={survey} />;
    }
    
    export default SurveyComponent;
    

    You can then include HTML in your titles like so:

    export const json = {
      elements: [
        {
          type: "checkbox",
          name: "Question1",
          title:
            "Check the box to continue",
          choices: [
            {
              value: 1,
              text: "I agree to the <a href='https://stackoverflow.com/legal/terms-of-service/public'>terms & conditions</a>",
            },
          ],
        },
      ],
      showQuestionNumbers: false,
    };
    

    Here's a full working example: https://codesandbox.io/p/sandbox/awesome-dust-6n4qf8?workspaceId=64c276ad-0dfc-48c8-9e36-39d45ffd6536

    IMPORTANT: Enabling HTML support as shown here is considered unsafe. Make sure you sanitize the HTML before applying it to the text labels.