Field Value-Based Submit Button Text

Knack Experts,

Is there a way to change the text on a submit button based on a form field value? Specifically, I have a yes/no field on a form that asks “Are you ready to submit this form?” If they select No, I would like the text on the Submit button to change to “Save”. If they answer yes, then the button would say “Submit”.

Thanks!

1 Like

Hi Jason,

You can achieve your goal using the following code:

Note: I’m assuming the Yes/No field is Radio input, as opposed to a checkbox or dropdown.

// This will change the Submit Button text depending on a field value.
// Note: Remember to update the view number and field number to yours.
$(document).on('knack-view-render.view_100', function (event, view, data) {
  const fieldKey = 'field_162'
  const $submitBtn = $(`#${view.key} button[type="submit"]`)
  const $input = $(`input[name="${view.key}-${fieldKey}"]`)

  function changeText() {
    const formValues = Knack.views[view.key].getFormValues()
    if (formValues[fieldKey] === 'Yes') {
      $submitBtn.text('Submit')
    } else {
      $submitBtn.text('Save')
    }
  }
  
  $input.on('change', function() {
    changeText()
  })

  changeText()
})

Ian
Knack Pros

2 Likes

Ian,

Thanks! Works great. Is there a way to do this with a yes/no drop-down box as opposed to radio buttons?

Hi Jason,

Replace this line:

const $input = $(`input[name="${view.key}-${fieldKey}"]`)

with:

const $input = $(`select#${fieldKey}`)

:+1:

1 Like

Thanks again @KnackPros.

I do not want you to put any more effort into this, but for some reason this seems to interfere with conditional error messages. I use a rule that says if an answer is blank, and the submit question is yes, present an error upon form submit. I cannot use required fields, as that forces people to put anything in a box even if they are not ready to answer yet – hence the “Save” aspect.

With this code, the error messages show up before anyone even presses Submit. If I fill in the questions, it works, but without all the fields filled in, it does not.

I may very likely use this some where else, so thank you again.

You’re welcome :v:

Regarding your conditional logic I’d have to take a closer look. Different moving parts.

Enjoy