Javascript Code for Checkboxes in List Not Working

Hello, I am trying to prepend checkboxes to one of my lists. I simply copied the code offered here:

http://helpdesk.knackhq.com/support/solutions/articles/5000447560-code-examples#jq-checkboxes

and changed the ViewID to what I believe is the correct ViewID for my app in two separate places in the code (as instructed). However, when I save and refresh the app, the checkboxes do not appear.

I'm unsure of what I did wrong. Any advice would be appreciated.

Thanks,

James

I've got this 90% working, however my update button only updates a single record in the table, and does not update all checked rows. I have followed this code presented here exactly. Did anyone else run into this issue?

The addition of the checkboxes works wonderful for all tables that don't have the totals ("Sum") row. Does anyone know how to have the totals row shop up under the correct column? I've spent nearly 4 hours already researching the issue. I can't find any solutions on the internet. Thanks ahead of time.

Dagmar - looks like learning code to me!

Here's the snippet I've used inside a button click event. I've included the code that grabs data from the table that I think you're having trouble with. Javascript experts would spot improvements I'm sure but it works.

checked.each(function() {
        Knack.showSpinner();
        var data_view_291 = Knack.models['view_291'].toJSON();
    var ProjectID = data_view_291.id;
    var ProjectDueDate = ConvertTextToDate(data_view_291.field_193);
    
    var Status = '551f5f4bf06e703c602d7745';	// Not Started
    var id = $(this).closest('tr').attr('id'); // record id
    var TaskName = $(this).closest('tr').children('td.field_181').text();
    var Category = $(this).closest('tr').children('td.field_182').text();
    var TaskDays = parseInt($(this).closest('tr').children('td.field_194').text());
    var TaskDueDate = AddDaysToDate(ProjectDueDate, TaskDays);
    var TaskOwnerID = data_view_291.field_37_raw;  // The project Owner ID
    var EmailList = data_view_291.field_141_raw;
    
    var data = { // define the fields you want to update
      field_23: ProjectID,
      field_15: TaskName,
      field_16: Category,
      field_84: Status,
      field_19: null,	//Reminder
      field_89: null,	//CompletedDate
      field_17: TaskDueDate,
      field_38: TaskOwnerID,
      field_162: EmailList
      //field_21: Priority
    };
       
      $.ajax({
          url: 'https://api.knackhq.com/v1/objects/object_5/records/',
          type: 'POST',
          headers: {'X-Knack-Application-ID': 'XXXX', 'X-Knack-REST-API-Key': 'XXXX'},
          data: data,
          success: function (response) { // each time an update completes, our success variable increases by 1
              success+=1;
                            
              if(success==calls) { // if the number of success calls = the number of checked boxes...
                  //Knack.hideSpinner();
                  window.location = '#projects/projectdetails2/' + ProjectID + '/tasks3/' + ProjectID + '/';
              }
          }
      });

  });</pre>

You should remove your App keys from your code in case someone wanted to access your data from this forum - just in case.

Hi Brad,

I got the insert part to work. I'm struggling, however with the part where I assign values to the target object from the checked table records in the data variable:

// Define the fields you want to update

var data = {

field_741: record_ids.field_283,

field_762: [record_ids.id],

field_751: record_ids.field_276,

field_751: [record_ids.id],

field_763: BuyerName,

};


I have copied my code here. Maybe you can see where I;m going wrong?


Thanks for the help.

Dagmar


var insertRecords = function(id, record_ids, data) {

$.ajax({
url: ‘https://api.knackhq.com/v1/objects/object_32/records’,// + id,
type: ‘POST’,
/***** CHANGE TO YOUR OWN APPID AND API KEY HERE *****/
headers: {‘X-Knack-Application-ID’: ‘578773182826ba663f18618d’, ‘X-Knack-REST-API-Key’: ‘4c515280-4a17-11e6-bfd3-6989fe28c9de’},
data: data,
success: function(response) {
if ( record_ids.length ) {
// Every time a call is made, the array is shifted by 1.
// If the array still has a length, re-run updateRecords()

    insertRecords(record_ids.shift(), record_ids, data);
    
  } else {            
    // We know all records are processed when length = 0
    alert('Update complete!');
    Knack.hideSpinner();
  }
}

})
}

/**** CHANGE VIEW_ID TO YOUR OWN VIEW ID ****/
$(document).on(‘knack-view-render.view_581’, function (event, view) {

// Add an update button
$(’<button id=“update”">Update</button>’).insertAfter("#knack-body");

// Add checkboxes to our table
addCheckboxes(view);

// Click event for the update button
$(’#update’).click(function () {

// We need an array of record IDs
var record_ids = [];
 
// Populate the record IDs using all checked rows
$('#' + view.key + ' tbody input[type=checkbox]:checked').each(function() {
  record_ids.push($(this).closest('tr').attr('id')); // record id
});
  
Knack.showSpinner();

var BuyerName = Knack.models['view_576'].toJSON().field_430_raw;

alert (BuyerName);  

// Define the fields you want to update
var data = {
  field_741: record_ids.field_283,
  field_762: [record_ids.id],
  field_751: record_ids.field_276,
  field_751: [record_ids.id],
  
  field_763: BuyerName,   
};
 
// Use the first ID in the array, then pass in the rest of the array
insertRecords(record_ids.shift(), record_ids, data);

$('#update').remove();

})
});

Hi Brad,

Thanks for the speedy reply. I am currently in the situation you found yourself in - being forced to learn Javascript and CSS, etc. To be honest, at the moment I don't write any code - I copy and paste and hack through it until it somehow works, so I would be very grateful if you can help.

Dagmar

Hi Dagmar,

Yes we use that function quite a lot and it works great. I reckon I have used an insert record function in one of my apps so I'll dig that out when I have some time.

In the meantime I recommend trawling through the API documentation and forum to understand how to insert records in the Knack console which is how I learned to do it. In fact I've confessed before that Knack pushed me to use Javascript for the first time (which I'm secretly grateful trying to move from Access VBA!).

Brad

Physiotherapist & Pretend developer

Hi Brad, I see from this thread that you use the 'add checkboxes to a table' code a lot. I really hope you can help me. I have been trying to use the example Nicolas posted here

http://helpdesk.knackhq.com/support/discussions/topics/5000039996

Instead of updating fields in the table though, I want to insert a new record in another object for each checked row. I suspect I have to change some things in the

var updateRecords = function(id, records, data) function and the code snippet where records are updated:

// Populate the record IDs using all checked rows

$('#' + view.key + ' tbody input[type=checkbox]:checked').each(function() {

record_ids.push($(this).closest('tr').attr('id')); // record id

});

I just don't know how or where.

Any help you can give would be very much appreciated.

Thanks!

James, if you're trusting you can add me as a shared builder using these instructions: http://helpdesk.knackhq.com/support/solutions/articles/5000522285-how-to-add-a-shared-builder-to-your-knack-app and using this email: brad(at)rehaboutcomes.com.au.

That didn't work either. How shall I give you access to the app?

Shouldn't matter but try switching the function ('addCheckBoxes') to after the view render code...

I used your advice and saw the same view number, please correct me if I'm looking at the wrong thing (see attached screenshots).

It would be great if you could take a look at the app if you don't see anything wrong here.

Thanks much!

That console error is a warning for a Knack library in use and not your code, and I suspect the second issue as you do - leading to the incorrect view number. Try inspecting the view you want checkboxes to confirm the view number in Chrome;

  1. right-click on the table and select Inspect Element
  2. look for #view_XXX within the elements and note the number - that should be the one to use

I'd be happy to take a look at the app if needed as a next step as it won't take long to fix I think.

Brad,

Thanks for the info. I checked the console and there appears to be a warning: "The key "target-densitydpi" is not supported". I think it has something to do with the view number.

In Knack, I went to the Interface tab, and located the correct page where I want the checkboxes to appear. This list only appears as a search result on the page that I designated as the view number in the javascript code. Could this be the problem? Otherwise, I don't know what else I would put as the view number. Could the page be pulling the list from another page, i.e. another view number?

Thanks again,

James

Hi James,

The console is a developers tool many browsers have - I use Chrome for example and a good help page is here https://developers.google.com/web/tools/chrome-devtools/?hl=en

Short answer: right click on your web page and choose 'Inspect Element' to open the developer tools, then choose 'Console' in the tabs to inspect any JavaScript errors.

If there's no errors reported then it might be the view number and I'd check the code again. I can vouch for the code posted here http://helpdesk.knackhq.com/support/solutions/articles/5000447560-code-examples#jq-checkboxes as I use it a lot.

Brad

Where would a console error appear?

There is code running before it, but I erased it and resubmitted, and the same problem occurred.

Did you get any console errors James?

Is there any other code running before the view render call to the addCheckboxes function?