SurveyJS: Get and assign default value to custom attribute

I am currently working on designing a custom property for the property grid that will allow users to choose from a dropdown menu which "attribute" they want to link to a specific question.

This attribute is essential in the project's business domain, and certain SurveyJS properties can be automatically configured based on the selected attribute. Essentially, the business domain model is intended to provide structure to the survey builder for domain validation purposes.

One of the SurveyJS properties affected by the attribute is the JSON property where the question's answer will be serialized into (valueName). This is how it is currently being implemented:

import { SurveyModel } from 'survey-core';

let choicesOptions : string[] = [];

export function setDomainAttributeChoices(choices: string[] ){
    choicesOptions = choices;
}

export const domainAttributeProperty = {
    name: 'DomainAttributeProperty',
    category: 'general',
    choices: loadChoices,
    visibleIndex: 0,
    onSetValue: onSetValue
}

function loadChoices(obj: unknown, cb: Function) {
    cb(choicesOptions);
}

function onSetValue(survey: SurveyModel, value: string): void {
    survey.setPropertyValue('valueName', value);
}

Please disregard the way choices are loaded; this method was chosen due to the nature of our shared library containing custom SurveyJS widgets, expressions, and attributes.

The current implementation works as expected – selecting an option from the dropdown sets the valueName property accordingly, resulting in a JSON output using the property names based on the attribute selection upon survey completion.

However, I would like to address the following issue (which occurs in the Survey Builder):

  1. I select a question and change the DomainAttribute property
  2. I deselect the question
  3. I select it again, but the custom property does not automatically reselect the previous value in the dropdown

I would like to have the ability, either upon focus of the question or during choice loading, to retrieve the question's valueName property and use it to automatically select the correct value in the choices list. Unfortunately, I have been unable to find documentation addressing whether this is possible.

If anyone could provide guidance on this matter, I would greatly appreciate it. Thank you!

Answer №1

After some investigation, I discovered that the issue was arising from how I was serializing the custom property in the question JSON. Instead of using DomainAttributeProperty, I was using valueName.

To resolve this, I implemented the following changes:

  1. Upon loading choices, I now read the valueName property of the question and assign it to DomainAttributeProperty. This ensures that the correct choice is selected when a question is refocused.

  2. I marked the custom property as non-serializable to prevent DomainAttributeProperty from appearing in the JSON.

The updated version is as follows:

import { Question } from 'survey-core';

let choicesOptions : string[] = [];

export function setDomainAttributeChoices(choices: string[] ){
    choicesOptions = choices;
}

export const domainAttributeProperty = {
    name: 'DomainAttributeProperty',
    category: 'general',
    choices: loadChoices,
    visibleIndex: 0,
    onSetValue: onSetValue
}

function loadChoices(question: Question, cb: Function) {
    const valueName = question.getPropertyValue('valueName');
    questionModel.setPropertyValue('DomainAttributeProperty', valueName);
    cb(choicesOptions);
}

function onSetValue(question: Question, value: string): void {
    question.setPropertyValue('valueName', value);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating actions safely with redux typesafety

I've made a mistake several times by forgetting to properly extract the connected action creator from props, as shown below: import {actionCreator} from 'my-actions'; interface Props { actionCreator: typeof (actionCreator); } const Foo: ...

Dealing with the Angular 7 ExpressionChangedAfterItHasBeenCheckedError in combination with NgsScrollReveal

Utilizing ngScrollReveal triggers a re-render with every scroll event. I am invoking a function through the HTML in this manner: <component [alternate]="toggleAlternate()"> The code for toggleAlternate() is as follows: toggleAlternate() { this.a ...

Accepting parameters in an Express POST requestWondering how to accept parameters in

Currently, I have an API that requires passing car make, model, and year in the URL. Using an express router post call, I am able to retrieve the query parameters and set them to an object. I need to ensure that the URL can accept parameters like this: lo ...

Iterating through an object in Javascript using dynamically changing property names

Is there an efficient way in Javascript to iterate through the property names of objects in an array? I have objects with properties from guest1 to guest100. Instead of manually looping through each property, is there a method to loop through all the gues ...

Encountering a Typescript error while attempting to utilize mongoose functions

An example of a User interface is shown below: import {Document} from "mongoose"; export interface IUser extends Document{ email: string; password: string; strategy: string; userId: string; isValidPassword(password: string): ...

Custom mapped type results in intermediate forms

I've recently developed a type in Typescript that explicitly blocks specific properties from objects/interfaces. This is necessary because Typescript's excess property checking only kicks in when an object literal is directly assigned, not when i ...

How to associate an object with a component in Angular2/TypeScript using HTTP

I am currently working on displaying a list of item names retrieved from a REST API. By utilizing the map function on the response observable and subscribing to it, I was able to obtain the parsed items object. Now, my challenge is how to bind this object ...

A more efficient method for incorporating types into props within a functional component in a TypeScript-enabled NextJS project

When dealing with multiple props, I am looking for a way to add types. For example: export default function Posts({ source, frontMatter }) { ... } I have discovered one method which involves creating a wrapper type first and then defining the parameter ty ...

Multiplying form inputs using JavaScript

I am working on an HTML form that includes arrays: <form method="post" id="formaa" name="form"> <div id="fields"> <div id="divas1" class="row"> <a href="#" id="did1" onClick="d(this);"><img src="d.jpg" /></a& ...

Halt the program's process until the ajax request has finished

Struggling with what seems like a common issue of the "Asynchronous Problem" and finding it difficult to find a solution. Currently, I am working on a custom bootstrap form wizard which functions as tabs/slideshow. Each step in the wizard is represented b ...

Running multiple instances of Chrome to execute all scenarios sequentially within a single feature file in Protractor

I need to run all scenarios in multiple instances of a browser. I've set the maximum instance value in capabilities, but only one instance of Chrome opens and the tests run sequentially. How can I ensure that the tests run in multiple instances simult ...

Having successfully configured and published Google Tag Manager, unfortunately, I am encountering difficulties in displaying the tag on the website

After setting up my GTM account and creating containers, tags, etc., I encountered an issue. Even after publishing my container and creating a version, when I checked my website, all the code was hidden within a div tag with display none and visibility hid ...

Utilizing AngularJS to create bound checkboxes

I am struggling with two checkboxes, one with Data Binding and the other without Data Binding. The code snippet below illustrates this: <html ng-app="notesApp"> <head><title>Notes App</title></head> <body ng-contro ...

Ensuring draggable div remains fixed while scrolling through the page

I am currently working on creating a draggable menu for my website. The menu is functional and can be moved around the page as intended. However, I have encountered an issue where the menu disappears when scrolling down the page due to its position attrib ...

A guide to writing a script to access and return a specific element stored in an array within an object's property

I have created this specific function function extractSingleValue<T, TElem, K extends keyof T>(obj: T, name: K): TElem { const source = obj[name]; if (source.length !== 1) { throw Error(`There should be exactly one ${name} associated`); } ...

Using eslint with the vue plugin allows you to specify which object fields to ignore in

My ESLint rule setup includes the following: "vue/script-indent": [ "error", 4, { "baseIndent": 1, "switchCase": 1, "ignores": [ "[init.type=\"ObjectExpression\"]", "[init.type= ...

Steps for creating a tileView from scratch

Have you noticed websites using a tile view layout lately? It seems like a popular trend. The concept involves having multiple elements on an HTML page with various widths and heights. These websites often use JavaScript to randomly arrange each element n ...

Tips for emphasizing specific sections of text in CodeMirror utilizing substring positions

I am currently utilizing CodeMirror () as a text editor with additional functionalities. One of these features includes highlighting specific words or groups of words based on their positions within the original string. I have an external structure that st ...

Determine if a cell is editable within the `renderEditCell` function by using MUI

I am working with a MUI data grid that contains different cell types. I am currently seeking a way to implement user permission-based editing for cells in the grid. However, I only want the permission testing to occur when a user attempts to edit a cell, r ...

Utilizing the power of JavaScript, CSS, and HTML to seamlessly transfer selected items from one webpage to the shopping cart displayed on another page

Due to limitations on using back-end code, I'm seeking advice on how to implement this function. Most tutorials I've come across show the items and shopping cart on the same page. I've heard suggestions about using Jquery.load(), but I&apos ...