This is a useful bit of code for long forms which saves the data from radio button submissions and sends them as view based put calls before pressing the submit button on the form.
Add/ Remove objects from the bind_to_inputs section to customize the # of pages, views and questions the code will trigger on.
Change the selection parameter for other types of inputs. Hope this helps someone. :)
bindListToInputs([
{
page_name: "page_xxx",
view_name: "view_yyy",
fields: [16, 18, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 101, 103, 105, 107, 109, 111, 113, 115, 117, 119, 121, 123, 125 ]
},
{
page_name: "page_zzz",
view_name: "view_nnn",
fields: [55, 57, 59, 61 ]
},
{
page_name: "page_ttt",
view_name: "view_jjj",
fields: [63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87 ]
},
{
page_name: "page_etc",
view_name: "view_etc",
fields: [89, 91, 93, 95, 97, 99 ]
},
]);
function bindListToInputs(list){
list.forEach(function(inputs){
bindToInputs(inputs);
})
}
function bindToInputs(inputs){
var page_name = inputs.page_name,
view_name = inputs.view_name,
fields = inputs.fields;
$(document).on("knack-view-render." + view_name, function(event, view, data) {
fields.forEach(function(fieldnum){
$("#kn-input-field_" + fieldnum).change(function(){
handleChange(fieldnum).then(function(result){
console.log("Record Updated with this data: ", result.input);
Knack.hideSpinner();
}, function(result){
alert('Update Failed!');
console.log(result.output.error);
})
});
})
});
function handleChange(fieldnum){
var fieldname = 'input[name=' + view_name + '-field_' + fieldnum + ']';
var data = {};
//change this attribute if you want a selector other than radio input.
var selection =$(fieldname + ':checked').val();
data['field_' + fieldnum] = selection;
console.log("selection is" + selection);
return makeRequest(data).then(function(resp){
return {
input: data,
output: resp
}
}, function(resp){
throw {
input: data,
output: resp
}
});
}
function makeRequest(data){
var url = window.location.href.split("/");
var recordid = url[url.length - 2];
var requestUrl = 'https://api.knack.com/v1/pages/' + page_name + '/views/' + view_name + '/records/'+recordid;
return $.ajax({
url: requestUrl,
type: 'put',
headers: {
'Authorization': Knack.getUserToken(),
'X-Knack-Application-Id': Knack.application_id,
'Content-Type': 'application/json'
},
data: JSON.stringify(data)
});
}
}