On the occasion where you want to restrict the State dropdown value to a set list (e.g. US states), below is a slice of code to replace the current text input with a selection list:
Insert the following code into the JavaScript section of your Knack app.
$(document).on('knack-view-render.any', function(event, view, data) {
const states = [
"", "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID",
"IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS",
"MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK",
"OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV",
"WI", "WY"
];
$("input#state.input").each(function () {
const currentValue = this.value;
const $stateComboBox = $("<select>", {
"data-placeholder": "Select",
"id": "state",
"name": "state",
"class": "select",
});
$.each(states, function(index, state) {
$stateComboBox.append($("<option>").text(state));
});
$stateComboBox.val(currentValue);
const $selectDiv = $("<div>", {
"class": "kn-select",
}).append($stateComboBox);
$(this).replaceWith($selectDiv);
});
});
-
states
will contain an array of all your State selections. If you’re Australian like me, you could replace the array with["","ACT","NSW","QLD","SA","TAS","VIC","WA"]
. I recommend keeping a blank selection at the start of the array. -
$stateComboBox
declares a<select>
element with similarid
andname
to the existing State field -
$selectDiv
declares a<div>
that matches properties of a native Knack combo box, so that the styling is maintained
I also highly recommend inserting this slice of code into the CSS section if your Knack app, which will give a little more room for the dropdown arrow:
/* Adjust City and Zip fields to give more room for State when in mobile view */
.kn-input-address .is-grouped>.control:first-child
{
flex: 3 !important;
}
.kn-input-address .is-grouped>.control:last-child
{
flex: 1 !important;
}
The result should look like below:
This solution works in regular and in-line editing forms, is compatible with auto-complete, but will not work in the Builder.
This piece of code can also be adjusted to replace any other text field with a combo box if you want to restrict other values (e.g. title in a name).