In this guide, we'll share how to set a custom field's value in a custom form on your website based on the type of field using JavaScript, allowing for dynamic form adjustments.
The script waits until the custom field elements are loaded, then finds the appropriate custom field based on the custom field name provided and modifies its value according to the specified type and input.
Users still need to submit the form in order for the values to be saved to the Piano database.
You can utilize this script to set different custom field types. Please note, that the code needs to be directly added to a template, most commonly the Piano ID custom form template.
function setCustomFieldValue(type, CF_name, value) {
if(type == "checkbox")
type = "boolean";
var timer = setInterval(() => {
if(document.querySelector(`${type}-custom-field`)) {
clearInterval(timer);
setTimeout(() => {
document.querySelectorAll(`${type}-custom-field`).forEach(cf => {
if(cf.querySelector(".sr-only").getAttribute("id") == CF_name + "label") {
if(type == "single-select") {
if(cf.querySelector(`.pn-dropdown [id="${value}item"]`).getAttribute("aria-selected") == "false")
cf.querySelector(`.pn-dropdown [id="${value}item"] div`).click();
}
else if(type == "text" || type == "date" || type == "number" || type == "phone-number") {
cf.querySelector(`input`).value = value;
cf.querySelector(`input`).dispatchEvent(new Event('input', { bubbles: true }));
cf.querySelector(`input`).dispatchEvent(new Event('change', { bubbles: true }));
}
else if(type == "boolean") {
if(cf.querySelector(`input`).checked != value)
cf.querySelector(`input`).click();
}
else if(type == "multi-line-text") {
cf.querySelector(`textarea`).value = value;
cf.querySelector(`textarea`).dispatchEvent(new Event('input', { bubbles: true }));
cf.querySelector(`textarea`).dispatchEvent(new Event('change', { bubbles: true }));
}
else if(type == "multi-select") {
value.forEach(v => {
if(cf.querySelector(`.pn-dropdown [id="${v}item"]`).getAttribute("aria-selected") == "false")
cf.querySelector(`.pn-dropdown [id="${v}item"] div`).click();
});
}
}
});
}, 1000); // setTimeout
} // IF ${type}-custom-field
}, 100); // timer
}
Where you can set the values as follows:
setCustomFieldValue("text", "custom_field_ID", "value");
setCustomFieldValue("multi-line-text", "custom_field_ID", "First line\nSecond line");
setCustomFieldValue("multi-line-text", "custom_field_ID_2", `First line
Second line`);
setCustomFieldValue("number", "custom_field_ID", 1234);
setCustomFieldValue("date", "custom_field_ID", "2004/01/25");
setCustomFieldValue("single-select", "custom_field_ID", "value");
setCustomFieldValue("multi-select", "custom_field_ID", ["value1", "value2"]);
setCustomFieldValue("checkbox", "custom_field_ID", true); // true or false
setCustomFieldValue("phone-number", "custom_field_ID", 421900123456); // phone number without the + sign