Question T11752
Visible to All Users

How to run javascript functions in the html type questions

created 3 years ago (modified 3 years ago)

Hey Team,

I am using Survey creator with React.

I want to run a javascript function like onclick event handlers, with the html type questions.

Here's html markup:

HTML
<button onclick="myFunction()">Click me</button> <p id="demo"></p> <script> function myFunction() { document.getElementById("demo").innerHTML = "Hello World"; } </script>

Here's my survey json:

Code
{ "title": "Demo Survey 1", "logoPosition": "right", "completedHtml": "<h3>Thank you for your feedback</h3>", "completedHtmlOnCondition": [ { "html": "<h3>Thank you for your feedback</h3> <h4>We are glad that you love our product. Your ideas and suggestions will help us make it even better.</h4>" }, { "html": "<h3>Thank you for your feedback</h3> <h4>We are glad that you shared your ideas with us. They will help us make our product better.</h4>" } ], "pages": [ { "name": "page1", "elements": [ { "type": "text", "name": "question1", "title": "What is your name?", "isRequired": true } ] }, { "name": "page2", "elements": [ { "type": "html", "name": "info", "html": "\n<button onclick=\"myFunction()\">Click me</button>\n\n<p id=\"demo\"></p>\n\n<script>\nfunction myFunction() {\n document.getElementById(\"demo\").innerHTML = \"Hello World\";\n}\n</script>" }, { "type": "text", "name": "question2", "title": "What is your age?" } ] } ], "showQuestionNumbers": "off" }

But here it throws error on click:

Code
Uncaught ReferenceError: myFunction is not defined at HTMLButtonElement.onclick (123:1:1)

Can you help me with this?

Thanks
Timi

Answers approved by surveyjs Support

created 3 years ago

Hi Timi,
The myFunction is not defined error message suggests there is something wrong with the myFunction accessibility. I created the following example: https://codesandbox.io/s/floral-tdd-qupq1k?file=/src/SurveyComponent.jsx.

I declared myFunction at the Form Library component, and added the myFunction property to the window object:

JavaScript
function myFunction() { document.getElementById("demo").innerHTML = "Hello World"; } window.myFunction = myFunction;

And it works fine for me. Please test this sample and let me know if you have any questions.

As a side question: why do you wish to execute a JS function from a survey element? Would you share a usage scenario?

Thank you

    Comments (2)

      Hi @Jane,

      I want to use html question in the survey creator, and that markup I want to bind the button event click handler.
      I already attached the survey creator JSON, in page 2 I have the HTML markup with the "myFunction" defined in <script> tag.

      And answer to your side question:
      I have an scenario where I have to call an API on that button click.

      Thanks
      Timi

        Hello Timi,
        Thank you for the clarification. Please let me know whether or not adding a custom function to the window object helps.