JavaScript & jQuery Examples

The following code examples have come from common requests, projects we've loved, code which users have shared with us, and other sources.

Many of these examples showcase how easily jQuery can be leveraged to make considerable changes UX within your app, such as hiding or showing specific elements in a specific view when certain conditions are met.

Another very common use for jQuery in custom code is to make AJAX calls from your Knack app. These often go to external - or you own app's - APIs. For some examples of this, take a look at our API code examples.

Customize message on “Forgot password?” page

This allows you to customize the text on the “Forgot password?” page.

$(document).on('knack-view-render.any', function(event, view, data) {
  $('#knack-reset-pass div h2').html('Test');  //your personalized text

  $('#knack-reset-pass div p').html('Test2');  //your personalized text
});

Catch changes to a specific field

If you want to trigger a certain action - for instance, an API call to make a follow-up change to a record - only when a certain field is changed, you can do so by:

  1. Nesting a knack-cell-update or knack-record-update listener inside a knack-records-render listener
  2. Identifying the record which was updated (if we're tracking an inline update in a table) by checking against the updated record's ID
  3. Comparing the value of the field(s) in question between the pre- and post-update versions of the record
  4. Taking an action of our choosing if the values are not identical
// Replace view_xx with the view key for the table view in question
// Replace field_yy with the field key for the field whose changes you want to track
$(document).on('knack-records-render.view_xx', function(event, scene, records) {
  $(document).on('knack-cell-update.view_xx', function(event, view, updatedRecord) {
    // Filter the initially loaded records for the one with the same ID as the updated one
    var recordBeforeUpdate = records.filter(recordFromRenderEvent => {
      return recordFromRenderEvent.id === updatedRecord.id;
    })[0];

    if (updatedRecord.field_yy !== recordBeforeUpdate.field_yy) {
      // Do something, such as:
      alert('Field_yy has been changed!')
    }

    $(this).off(event)
  });
});

Replace text on all submit buttons

// This would update the text on every single view across the app
// Use for all themes except for the Knack Standard Theme
$(document).on('knack-scene-render.any', function(event, scene) {
  $(".kn-submit input[type=submit]").attr("value", "Press me");
});

// Use for the Knack Standard Theme
$(document).on('knack-scene-render.any', function(event, scene) {
  $(".kn-submit button").html("Press me");
});

Add color to a specific field value in a view

This allows you to add color to specific fields. For example, showing the word “Expired” or “Rejected” in red text, or maybe making the text green if it is “Approved.” This example will change the text to red if the value is “Expired” otherwise it sets it to green.

// Replace view_1 and field_2 with your view and field keys
$(document).on('knack-view-render.view_1', function(event, view, data) {
  $("#view_1 td.field_2").each(function() {
    // #ff0000 is red and the #1c631f is green
    var textColor = ($(this).find("span").text().trim() == "Expired") ? "#ff0000" : "#1c631f";
    $(this).css("color", textColor);
    })
});

Moving the signup link

This example allows you to move the Signup link above the log in form. You could also add other CSS to the link to make it more visible if you wanted.

// Replace view_1 with your view key
$(document).on('knack-view-render.view_1', function(event, scene) {
  $("#view_1 .register").insertAfter($("#view_1 .view-header"));
});

Custom form validation

This example allows you to set a specific validation requirement for a field when submitting a form.

// Replace view_1 and field_1 with your view and field keys
// Use on all themes except the Knack Standard theme
$(document).on('knack-view-render.view_1', function(event, view, data) {
  $("#view_1 .kn-submit input[type=submit]").on("click", function() {
    // If this value in the form doesn't equal "SpecificValue" then prevent the form from submitting
    if ($('#view_1 #field_1').val() != "SpecificValue") {
     alert ("These are not the droids you are looking for.");
     return false;
    }
  })
});

// Use on the Knack Standard Theme
$(document).on('knack-view-render.view_1', function(event, view, data) {
  $("#view_1 .kn-button").on("click", function() {
     // If this value in the form doesn't equal "SpecificValue" then prevent the form from submitting
     if ($('#view_1 #field_1').val() != "SpecificValue") {
      alert ("These are not the droids you are looking for.");
      return false;
    }
  })
});

Add checkboxes to a table

This example allows you to add checkboxes to a table, including a check all/none checkbox in the header.

// Function that adds checkboxes
var addCheckboxes = function(view) {
  // Add the checkbox to to the header to select/unselect all
  $('#' + view.key + '.kn-table thead tr').prepend('<th><input type="checkbox"></th>');
  $('#' + view.key + '.kn-table thead input').change(function() {
    $('.' + view.key + '.kn-table tbody tr input').each(function() {
      $(this).attr('checked', $('#' + view.key + '.kn-table thead input').attr('checked') != undefined);
    });
  });
  // Add a checkbox to each row in the table body
  $('#' + view.key + '.kn-table tbody tr').each(function() {
    $(this).prepend('<td><input type="checkbox"></td>');
  });
}
// Add checkboxes to a specific table view (view_1). Replace view_1 with your view key
$(document).on('knack-view-render.view_1', function (event, view) {
  addCheckboxes(view);
});
// Cycle through selected checkboxes. Use this in any code that needs to get the checked IDs
$('#view_5 tbody input[type=checkbox]:checked').each(function() {
  // add code here to get record id or row value
  var id = $(this).closest('tr').attr('id'); // record id
});

Move the back link below the crumbtrail

This will move the backlink (ex. “Back to Client”) at the bottom of the page, directly below the crumbtrail (ex. Client > Client Details) at the top of the page. This will change will affect every page in the app.

$(document).on('knack-scene-render.any', function(event, scene) {
   $(".kn-view.kn-back-link").insertAfter( $(".kn-view.kn-info.clearfix") );
});

Disable form input field

This example will disable the text input field in a form.

// Replace scene_1, view_1, and field_1 with your scene, view, and field keys
$(document).on('knack-scene-render.scene_1', function(event, scene) {
    $('#view_1 #field_1').attr('disabled', 'disabled');
});

Change the text in the back link

This example will allow you to change the back link URL for a specific scene. Change scene_# to "any" to apply to all scenes.

$(document).on('knack-scene-render.scene_##', function(event, scene) {
$(".kn-back-link a").attr("href", "New URL")
});

Convert input text to uppercase

This example will convert any text you input in the specified text to UPPERCASE as you type it.

$(document).on('knack-view-render.any', function (event, view, data) {
  // Remove #field_1 so it works for ALL inputs
  // Use $('input:not(#email, #password)') to exclude emails and passwords for logins
  // Replace field_1 with your field key
  $('input#field_1').keyup(function() {
      this.value = this.value.toUpperCase();
  });
});

Capitalize input text

This example will capitalize any text in the specified input and ignore all characters after the first one.

$(document).on('knack-view-render.any', function (event, view, data) {
// Remove #field_1 so it works for ALL inputs
  $('input#field_1').keyup(function() {
      this.value = this.value.charAt(0).toUpperCase() + this.value.slice(1);
  });
});

Set Connection Field

This example demonstrates how to programmatically update a connection field in a form view. You will need the record id for the connected value to populate the field and then trigger an update on the dropdown field to visually render the change.

$(document).on('knack-view-render.view_52', function(event, view, data) {
	// The connected record id value
	var connectionId = "5b2ac7fc66b6036b8f859c45";

	// Update the view and field ids for your application
	$('#view_52-field_3').val(connectionId);
	$('#view_52-field_3').trigger("liszt:updated");
});

Change the options in the time field

This example will change the range of time options available in the timer field in a form.

/* Change the field and view numbers to match the view and field in your app.*/
$(document).on('knack-view-render.view_8', function(event, view, data) {
  $('#view_8-field_59-time').timepicker('option', 'minTime', '2:00pm');
  $('#view_8-field_59-time').timepicker('option', 'maxTime', '11:30pm');
});

Change the 'add filter’ text

This example will change the 'add filter’ text for any view.

$(document).on('knack-view-render.any', function(event, view, record) {
  $('.kn-add-filter').text('Advanced Search')
});

Redirect the user after an e-commerce checkout

This example will redirect the user after they submit a Checkout form.

$(document).on('knack-checkout-submit.any', function(event, view, record) {
  window.location.replace('https://yoururlgoeshere.com');
});

Redirect Live App to HTTPs

This example will redirect the user to the https page, if they load a page at http.

/* Change the scene_1 to the scene key of your choice, or any to redirect on all pages. */
$(document).on('knack-scene-render.scene_1', function(event, scene) {
  if (location.protocol != 'https:')
  {location.href = 'https:' + window.location.href.substring(window.location.protocol.length);}
});

Change Keyword Search Placeholder Text

This example changes the placeholder text for a keyword search.

Note: This code example will only applies to the Keyword search field shown on Table and List views.

/* Change the scene_1 to the scene key of your choice, or any to change on all pages. */
$(document).on('knack-scene-render.scene_1', function(event, scene) {
  $("input[name='keyword']").attr("placeholder", "Type your replacement text here")
});

Move Field Instructions Above Input Box

This example will move the instructions on a form field, above the input box.

/* Change the scene_1 to the scene key of your choice, and field_1 to the field key of the field you're working with. */
$(document).on('knack-scene-render.scene_1', function(event, scene) {
  $('#kn-input-field_1 > p.kn-instructions').prependTo($('#kn-input-field_1 div.kn-radio'));
});

Auto-Submit Form When Page Loads

This example will submit a form when a page is loaded.

/* Change the scene_1 to the scene key of your choice. */
$(document).on('knack-scene-render.scene_1', function(event, scene) {
    // Knack Standard Theme:
    $('button[type=submit]').submit();

    // Legacy: Classic and Legacy: Flat Themes:
    $('input[type=submit]').submit();
});

Hide Empty Tables

This example will hide tables that contain no data.

/* Change the scene_1 to the scene key of your choice, or replace with any to work on all pages. */
$(document).on('knack-scene-render.scene_1', function(event, scene) {
  // Loop through each scene view, on the page.
  scene.views.map(function(view) {
    // If view has row data and that data is less than 1...
    if(Knack.models[view.key] && Knack.models[view.key].data && Knack.models[view.key].data.length < 1) {
      // Remove the specific view.
    	$('#' + view.key).remove();
    }
  });
});

Redirect User After Logout

This example will allow you to redirect users to a specific page after they logout of the Live App.

/* Change the scene_1 to the scene key of your choice, or replace with any to work on all pages. */
$(document).on('knack-scene-render.scene_#', function(event, scene, data) {
  $("a.kn-log-out").on("click", function() {
    // Some browsers need some wait-time to finish the logout
    setTimeout(function(){
        // replace with your desired URL
        window.location = "URL-GOES-HERE";
    }, 500);
  })
});

Change Calendar Start Date

This example will allow you to change the start date when a calendar view is loaded.

/* Change the scene_1 to the scene key of your choice, or replace with any to work on all pages. */
$(document).on('knack-scene-render.scene_#', function(event, scene, data) {
  var url = window.location.href;
  	url += "?view_#_date='2018-05-01'"
  window.location.href = url;
});

Change Tab Name in Live App

This example will allow you to change the tab name when a page is loaded in your Live App.

/* Change the scene_1 to the scene key of your choice, or replace with any to work on all pages. */
$(document).on('knack-scene-render.scene_1', function(event, scene) {
  document.title = 'Tab Name Here';
});

Use a Custom Icon for saving your App to a mobile device's Home Screen

This example will allow you to use a personalized icon when user's save the Mobile Web App to their Home Screen.

/* Change the below icons to your personalized icon links. */
$("head").append("<link rel='apple-touch-icon-precomposed' sizes='57x57' href='icon.png' />");
$("head").append("<link rel='apple-touch-icon-precomposed' sizes='72x72' href='icon.png' />");
$("head").append("<link rel='apple-touch-icon-precomposed' sizes='114x114' href='icon.png' />");
$("head").append("<link rel='apple-touch-icon-precomposed' sizes='144x144' href='icon.png' />");

Get Signature Data from Form

This example will allow you to get the raw data from a Signature Field inside a form.

/* Change the below view id and field id for your application */
  $(document).on('knack-view-render.view_xx', function(event, view, records) {
    // Get SVG And Base30 Data
    var svgData = $("#view_xx-field_xx").jSignature('getData','svg')[1];
    var base30Data = $("#view_xx-field_xx").jSignature('getData','base30')[1];

    // From here you can do something with the raw data
  });

Hide the Menu for a Specific Scene

This example will allow you to hide the application menu for only a specific scene. For a simple way to hide the menu on all pages, see this CSS example here.

/* Change the below scene_1 to the specific scene for your application */
  $(document).on('knack-scene-render.scene_1', function(event, scene) {
      $('#kn-app-menu').hide()
  });

Prevent Modals from Closing with a Click

This example will prevent a modal from being closed when the background outside of the modal is clicked. This can be done for a specific scene or all scenes.

/* Change the below scene_1 to the specific scene for your application or use `any` to enable for all scenes */
  $(document).on('knack-scene-render.scene_1', function(event, scene) {
    $('.kn-modal-bg').off('click');
  });

Change text on SSO buttons on login page

This example will allow you to customize the text on SSO buttons on a login page.

/* Change the below scene_1 to the specific scene for your application or use `any` to enable for all scenes */
  $(document).on('knack-scene-render.scene_1', function(event, scene) {
    $("a.kn-button.is-google").html("Enter custom text here")
    $("a.kn-button.is-facebook").html("Enter custom text here")
    $("a.kn-button.is-twitter").html("Enter custom text here")
  });

Customize Login Page Text and Labels

This example allows you to customize all the text and labels on a login page.

/* Change text on login page (buttons and labels) */
$(document).on('knack-view-render.view_##', function(event, view) {
	$("h2.kn-title").html('Custom Text')  //login page h2 text
	$("p.kn-description").html('Custom Text')  //login page instructions text
	$("label.kn-label[for=email]").html("Custom Text") //email input label text
	$("label.kn-label[for=password]").html("Custom Text") //password input label text
	$("input.kn-button.is-primary").attr("value","Custom Text") //submit button text
	$("label.remember").html("Custom Text") //remember me label text
	$("span.kn-label").html("Custom Text") //need an account? register label text
	$("a.register.kn-button").html("Custom Text") //register button text
});