Setting a field value in Nextgen with Javascript

Playing with Nextgen apps and as pointed out by @StephenChapman setting field values in Javascript is a different beast than in classic apps. this is a cornerstone of the complex apps we’ve been running for nearly 10 years in Knack and I’m certain is crucial for other builders here.

What doesn’t work

Inside a view or scene render event:

document.querySelector('input#view_7-field_16').value = "TEST";

If this field doesn’t receive focus at all and the form is submitted the field remains blank. Trial and error showed a different story if the field ever received user focus, so…

What does work

let field = document.querySelector('input#view_7-field_16');
field.value = "TEST";
field.focus();

Why and what’s next - help from coders

I’m assuming setting the focus changes the field or form state somewhere that is different to setting the value in the DOM (which was enough in Classic apps). I’m not formally IT trained so I don’t know enough, and AI suggests weird workarounds including using dispatchEvents for Input and Change but for every field likely to be impacted.

And I’m certain we don’t want to run .focus() for every field set with less than ideal UI impacts.

Perhaps some sort of Form method is available that bubbles DOM changes up to set the state?

Hey @BradStevens,

I believe it relates to the issue we discussed in this thread. I’ve just logged a ticket, so hopefully we’ll get answers as to whether it’s a bug or intentional, and whether there is a hidden method we can use.

Hi Team,
I’m trying to update an input value using JS using something like:
document.querySelector('input#view_11-field_38_street').value = '123 TEST ST';
This value does not persist when switching to another input on the form or submitting the form.
I can see using this new method Knack.page.getForm('view_11').getValues() that the value is not being updated after setting it via JS.
Here is a video I recorded recently from this forum thread to show you the behaviour.
2025-12-03, Knack, Next-Gen Input Change Via JS.mp4
I’m curious to know if it will still be possible to update input values using JS, or if there is another method that should be used. Thanks.

1 Like

@StephenChapman trialed ways to dispatchEvents without success FYI:

// Function to sync all fields in a specific Knack view
  const syncKnackForm = (viewId) => {
    const viewElement = document.getElementById(viewId);
    if (!viewElement) return;

    // Select all common input types
    const inputs = viewElement.querySelectorAll('input, textarea, select');

    inputs.forEach(input => {
      // Trigger both 'input' and 'change' to cover all React listener variations
      input.dispatchEvent(new Event('input', { bubbles: true }));
      input.dispatchEvent(new Event('change', { bubbles: true }));
    });
  };

@StephenChapman did you get any feedback on this one?

Not just yet. @Kara? :slight_smile:
There were some exciting developments for some new Next-Gen functions that will populate form fields without needing to target the element.

There’s still a few glitches though, as the set values are not being updated live on the form, and setting some field types isn’t working as expected.

Here’s an example:

Knack.ready().then(async () => {
  Knack.on('page:render', () => {
    const form = Knack.page.getForm('view_38');
    if (!form) return;

    form.setValue('field_1', 'Project A'); // Text
    form.setValue('field_2', 25); // Number
    form.setValue('field_3', { first: 'Stephen', last: 'Chapman' };

    form.onFormChange = ({ changedFieldKey, changedValue }) => {
      if (changedFieldKey === 'field_1') { 
        // Do something when field_1 changes
      }
    };

    form.onBeforeSubmit = ({ values, errors }) => {
      if (values['field_55']) {
          return true; // Allow form to be submitted
        } else {
          form.setError('field_55', {
            message: 'This value is required!'
          });
          return false; // Prevent form being submitted
        }
    };

  });
});

Could you send me more details about the field types, and I will add them to the ticket?

2 Likes

Thanks @Kara - this is probably the remaining barrier for us to move any apps of significance into testing Next-gen for us.

@BradStevens @StephenChapman

There’s a few tickets I can give updates on -

setValue() - It updates the value in the background (in form.getValues(), but it doesn’t seem to visually update on the form’s input. Additionally, it looks like setValue is not working on number, currency, date, timer, and rich text fields

  • This is queued up for the engineer to take :hourglass_not_done:

view:render does not fire after form auto-reloads on submit. When a form view has “Automatically reload the form” enabled on submit, the form visually reloads after submission, but the view:render event is not triggered again for that view. As a result, any JS logic relying on view:render does not run after the reload.

  • This will be included in next Tuesday’s release :star_struck:

Race condition causes user.token to be undefined in Knack.getUser(). When calling Knack.getUser() in Next-Gen apps, the user.token property is frequently undefined even when the user is logged in and other user properties (email, name, id) are available

  • This will be included in next Tuesday’s release :star_struck:
  • NOTE - The engineers were never able to replicate this locally. However, based on customer feedback, they have implemented a preventive fix that addresses the timing issue by adding a waitForSessionToken() helper function that waits up to 2 seconds for the session token to become available before proceeding with the API call. This provides a more robust solution than the customer’s workaround delay, as it actively checks for token availability rather than using a fixed timeout. The fix modifies the userQuery() function in customJsQueries.ts to use this waiting mechanism instead of immediately accessing cached session data, and includes fallback protection to ensure tokens are included in the response even if timing issues persist. The implemented solution should resolve the inconsistent user.token availability that customers have been experiencing in their custom code. If this still occurs after the release, please let us know.

New: Expose getFilters() method for views

  • Will be included in next Tuesday’s release :star_struck:

    window.Knack.ready().then(() => {
    console.log(‘Testing getViewFilters…’);
    
    const viewKey = ‘view_xx’; // replace with the view key that has filters
    const filters = window.Knack.page.getViewFilters(viewKey);
    
    console.log(Filters for ${viewKey}:, filters);
    });
    

JS .focus() question from @StephenChapman

  • Still queued up for Eng to respond to :hourglass_not_done:

What doesn’t work

Inside a view or scene render event:

document.querySelector('input#view_7-field_16').value = "TEST";
If this field doesn’t receive focus at all and the form is submitted the field remains blank. Trial and error showed a different story if the field ever received user focus, so…

What does work

let field = document.querySelector('input#view_7-field_16');
field.value = "TEST";
field.focus();
Why and what’s next - help from coders

I’m assuming setting the focus changes the field or form state somewhere that is different to setting the value in the DOM (which was enough in Classic apps). I’m not formally IT trained so I don’t know enough, and AI suggests weird workarounds including using dispatchEvents for Input and Change but for every field likely to be impacted.

And I’m certain we don’t want to run .focus() for every field set with less than ideal UI impacts.

Perhaps some sort of Form method is available that bubbles DOM changes up to set the state?

Released & Available, will be announced next Tuesday: :star_struck:

Examples for getForm, getValues, onBeforeSubmit, onFormChange and setError

Knack.ready().then(async () => {
  Knack.on('page:render', () => {
    // Attempt to fetch the form view with key 'view_38'.
    // If this view key does not exist on the current page,
    // Knack.page.getForm() will return null.
    const form = Knack.page.getForm('view_38');
    // IMPORTANT SAFETY CHECK:
    // This prevents runtime errors when:
    // 1. The view key exists but is NOT a form view
    // 2. The form is not present on the current page
    // Without this guard, accessing form methods would crash the page.
    if (!form) {
      return;
    }
    console.log('form: initial values on render', form.getValues());
    // Runs every time a form field value changes.
    // Receives the changed field key and its new value.
    form.onFormChange = ({ changedFieldKey, changedValue }) => {
      console.log('form: changedFieldKey', changedFieldKey);
      console.log('form: changedValue', changedValue);
    };
    // Runs right before the form is submitted.
    // Allows validation, modification, or blocking of submission.
    form.onBeforeSubmit = ({ values, errors }) => {
      console.log('form: errors onBeforeSubmit', errors);
      console.log('form: values onBeforeSubmit', values);
      // Custom validation rule:
      // Only allow submission if field_49 has the value 'valid'
      if (values['field_49'] === 'valid') {
        console.log('form: valid value, allowing submission');
        return true; // Proceed with form submission
      }
      // If validation fails:
      // 1. Prevent form submission
      // 2. Attach a custom error message to the field
      console.log('form: invalid value, aborting submission');
      form.setError('field_49', {
        message: 'This value is very very bad'
      });
      return false; // Abort form submission
    };
  });
});

Released and Available, (but not announced yet, note the first point about setValues above) and reset feature :hourglass_not_done:

Knack.ready().then(async () => {
  Knack.on('page:render', () => {
    const form = Knack.page.getForm('view_38');
    if (!form) {
      return;
    }
    /* ------------------------------------------------------------------
       Feature: Programmatically set initial field values
       ------------------------------------------------------------------
       These values are applied when the page renders.
       Useful for:
       - Pre-filling known user data
       - Setting defaults based on context
    */
    // Set a text field value
    form.setValue('field_1', 'John Doe');
    // Set a number field value
    form.setValue('field_2', 25);
    // Set a complex field value (e.g. email or connection field)
    // using the expected object structure
    form.setValue('field_3', {
      email: 'john@example.com',
      label: 'Work Email'
    });
    /* ------------------------------------------------------------------
       Feature: Conditional form reset with default values
       ------------------------------------------------------------------
       Listens for changes to form fields and performs
       a full reset when a specific condition is met.
    */
    // Triggered whenever any field value in the form changes
    form.onFormChange = ({ changedFieldKey, changedValue }) => {
      // Check if a specific field (field_4) was updated
      // and whether its value matches the reset condition
      if (changedFieldKey === 'field_4' && changedValue === 'Yes') {
        // Reset the form to its original state
        // This clears user input and restores initial values
        form.reset();
        // Re-apply default values after reset
        // (reset() removes all programmatically set values)
        form.setValue('field_5', 'United States');
        form.setValue('field_6', 'Active');
        // Log for debugging and verification
        console.log('Form has been reset and default values reapplied');
      }
    };
  });
});

Cheers,

Kara

3 Likes

Thank you @Kara, you deserve a raise!
I think .focus() isn’t as important if the .setValue() works. :slight_smile:

2 Likes

Agree with @StephenChapman - getting .setValue() to work will solve this issue. Thanks so much.

1 Like

@BradStevens @StephenChapman The fix for user.token being undefined in Knack.getUser() has been released, please let me know if it is not resolved for you.

1 Like

Also, the form.setValue work is under review, and hopefully should be released next week.

2 Likes

Thanks for working on this - any update @Kara ?

Hi @BradStevens it is still in QA - hopefully soon :folded_hands:

1 Like

Thanks @Kara - looks solved from today’s update: https://docs.knack.com/reference/record-and-form-events#formsetvalue-method

I haven’t tested yet.

@BradStevens we are investigating a possible issue with the form.focus method, so will need to test the .setValue() too. I’ll keep you posted.

1 Like

Hi all,

Yesterday in the release notes we announced:

  • New: Custom Code - form.focus() Method (Next-Gen) &

  • Fixed: Custom Code - form.setValue() Now Updates Field Display (Next-Gen)

This code has been reverted as it was causing an issue that was not caught despite extensive testing. On Monday, we will start working on the fix so we can safely re-release it.

I have removed the references from the developer documentation, but I have not updated the release notes as everyone would be emailed again.

Thanks for your patience with this and I’ll keep you posted with developments next week.

Kara

1 Like