0

I have this form enter image description here And this code for the form is like this:

.form-group.form-item.row
   = hidden_field_tag "test_method_id", @test_method.id, id: 'test_method_id'
   .col-sm-3
     %label Signature Title
      = text_field_tag 'signature_title', nil, class: 'form-control', placeholder: 'Enter Signature Title'
   .col-sm-3
     %label Add Required Certificate Types
      = collection_select :signature_requirement, :certificate_ids, @certificates, :id, :name, { selected: @test_method.certificate_ids, include_blank: "Select Certificate Type" }, { class: "form-control select2 multi-select2", multiple: "multiple" }

   .col-sm-2
     %label.small Mandatory Signature
     .form-check.mt-2.text-center
       = check_box_tag 'mandatory', 'mandatory', false, class: 'form-check-input'
   .col-sm-2
     %label.small Show Signature in Report
     .form-check.mt-2.text-center
       = check_box_tag 'include_in_report', 'include_in_report', false, class: 'form-check-input'
   .col-sm-2
     .icon.text-center
       %i#create-signature-requirement-btn.fa.fa-plus-circle.add-icon

The main focus is on the checkboxes, I want to get this value sent to rails, but they are not getting passed to the params, I have no idea why.

Read a few StackOverflow answers and documentation but I can't find the right solution.

How do I get the value of the checkbox to be passed - to rails, uncheck the checkbox (on ajax success) and then have it checked when appended to the table?

Here's the code that gets the values of title and certificates types appended to the table at the moment.

$('#create-signature-requirement-btn').on('click', function(event) {
    event.preventDefault();

    let testMethodId = $('#test_method_id').val();
    let signatureTitle = $('#signature_title').val();
    let certificateIds = $('#signature_requirement_certificate_ids').val();

    $.ajax({
      url:
        '/settings/test_methods/' + testMethodId + '/add_signature_requirement',
      dataType: 'json',
      method: 'POST',
      data: {
        signature_requirement: {
          signature_title: signatureTitle,
          certificate_ids: certificateIds
        }
      },
      success: function(data) {
        console.log(data);
        appendSignatureRequirement(data);
        $('#signature_title').val('');
        $('#signature_requirement_certificate_ids')
          .val(null)
          .trigger('change');
      }
    });
  });

This is the code for the appendSignatureRequirement() function:

function appendSignatureRequirement(record) {
  row = $('#signature_requirement_' + record['id']);
  texts = $('#signature_requirement_certificate_ids').select2('data');
  var html =
    '<td>' +
    non_null(record['signature_title']) +
    '</td>' +
    '<td>' +
    extractTextFromMultiSelect(texts) +
    '</td>' +
    '<td>' +
    "<a class='mr-2' href='javascript:editSignatureRequirement(" +
    record['id'] +
    ")'>" +
    "<i class='fa fa-pencil text-secondary' aria-hidden='true' data-toggle='tooltip' title='Edit'></i>" +
    '</a>' +
    "<a href='javascript:deleteSignatureRequirement(" +
    record['id'] +
    ")'>" +
    "<i class='fa fa-trash text-danger' aria-hidden='true' data-toggle='tooltip' title='Delete'></i>" +
    '</a>' +
    '</td>';
  if (!row.length) {
    row = $('#signature_requirements').append(
      "<tr id='signature_requirement_" + record['id'] + "'>" + html + '</tr>'
    );
  } else {
    row.empty();
    row.append(html);
  }
}

and here is my database table:

 => SignatureRequirement(id: integer, signature_title: string, mandatory: integer, include_in_report: integer, test_method_id: integer, created_at: datetime, updated_at: datetime)

This is the code for the table, displaying the values:

    .col-sm-10
      .table-responsive.mt-5
        %table.table.table-hover.table-valign-middle
          %thead
            %tr
              %th Title
              %th Certificate Types
              %th Mandatory
              %th Show in Report
              %th Actions
          %tbody#signature_requirements
            - @test_method.signature_requirements.each do |signature_requirement|
              %tr{:id => "signature_requirement_#{signature_requirement.id}"}
                %td
                  = signature_requirement.signature_title
                %td
                  - signature_requirement.certificates.each do |certificate|
                    %span.badge.badge-pill.badge-primary
                      = certificate.name
                %td
                  %a.mr-2{:href => "javascript:editSignatureRequirement(#{signature_requirement.id})"}
                    %i.fa.fa-pencil.text-secondary{"aria-hidden" => "true", "data-toggle"=>"tooltip", "title"=>"Edit"}
                  %a{:href => "javascript:deleteSignatureRequirement(#{signature_requirement.id})"}
                    %i.fa.fa-trash.text-danger{"aria-hidden" => "true", "data-toggle"=>"tooltip", "title"=>"Delete"}
mayorsanmayor
  • 2,870
  • 4
  • 24
  • 44

2 Answers2

2

Please try below code for get checked checkbox values.

$('#create-signature-requirement-btn').on('click', function(event) {
    event.preventDefault();
    let testMethodId = $('#test_method_id').val();
    let signatureTitle = $('#signature_title').val();
    let certificateIds = $('#signature_requirement_certificate_ids').val();

    let mandatory = $("input[name='mandatory']:checked") ? 1 : 0;

    let include_in_report= $("input[name='include_in_report']:checked") ? 1 : 0;

    $.ajax({
    url:
            '/settings/test_methods/' + testMethodId + '/add_signature_requirement',
            dataType: 'json',
            method: 'POST',
            data: {
            signature_requirement: {
            signature_title: signatureTitle,
                    certificate_ids: certificateIds,
                    mandatory: mandatory,
                    include_in_report: include_in_report,
            }
            },
            success: function(data) {
            console.log(data);
            appendSignatureRequirement(data);
            $('#signature_title').val('');
            $('#signature_requirement_certificate_ids')
                    .val(null)
                    .trigger('change');
            }
    });
    });
stalinrajindian
  • 1,363
  • 1
  • 14
  • 22
  • Thanks for your answer, this should work when the value has been passed and created in rails right? But at the moment the value doesn't even get passed - See my question `How do I get the value of the checkbox to be passed, uncheck the checkbox and then have it checked when appended to the table?` Your answer only answers this - `have it checked when appended to the table` what about the first 2? – mayorsanmayor Oct 21 '18 at 10:22
  • @mayorsanmayor your checkbox value is saved or not in DB. – stalinrajindian Oct 21 '18 at 10:31
  • not yet saved. this what the console looks like currently when the checkbox is checked. please check the code of my `check_box_tag` – mayorsanmayor Oct 21 '18 at 10:35
  • `SignatureRequirement Create (40.9ms) INSERT INTO "signature_requirements" ("signature_title", "test_method_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["signature_title", "Test"], ["test_method_id", 1], ["created_at", "2018-10-21 10:32:32.612779"], ["updated_at", "2018-10-21 10:32:32.612779"]]` `CertificatesSignatureRequirement Create (1.8ms) INSERT INTO "certificates_signature_requirements" ("certificate_id", "signature_requirement_id") VALUES ($1, $2) [["certificate_id", 1], ["signature_requirement_id", 33]]` – mayorsanmayor Oct 21 '18 at 10:35
  • I have updated the parameter, Can you please check it. signature_requirement: { signature_title: signatureTitle, certificate_ids: certificateIds, mandatory: mandatory, include_in_report: include_in_report, } – stalinrajindian Oct 21 '18 at 10:47
  • Okay thank you, that didn't work, because the values in if were not available outside the conditional scope. However, I refactored a bit to make it work, thanks for giving me the idea. Here's the code - `let mandatory = $("input[name='mandatory']:checked") ? 1 : 0; let include_in_report = $("input[name='include_in_report']:checked") ? 1 : 0;` - you should update your answer with this, incase somebody else checks in the future. Now how do we uncheck unpon successful creation in db? and how do we append to the table? – mayorsanmayor Oct 21 '18 at 11:01
  • found a way to uncheck the checkbox - https://stackoverflow.com/a/17420580/5012862 tested it and it worked. Going to work on appending to the table next. – mayorsanmayor Oct 21 '18 at 11:17
0

I was able to solve the problem. Thanks to this answer for getting me started.

This is the full implementation:

Extract text from multi-select box and remove the comma from the array generated by the map function

function extractTextFromMultiSelect(record) {
  if (record.length === 0) {
    return '';
  } else {
    let texts = $.map(record, function(obj) {
      span =
        '<span class="badge badge-pill badge-primary">' + obj.text + '</span>';
      return span;
    });
    return texts.join(' ');
  }
}

using HTML's checked property, check the checkbox if checked and null if not

function extractMandatoryCheckbox() {
  let mandatory = $('input[name="mandatory"]').prop('checked')
    ? 'checked'
    : null;
  return `<div class="form-check text-center">
    <input type="checkbox" class="form-check-input mb-4" ${mandatory}>
    </div>`;
}

function extractShowInReportCheckbox() {
  let include_in_report = $('input[name="include_in_report"]').prop('checked')
    ? 'checked'
    : null;
  return `<div class="form-check text-center">
    <input type="checkbox" class="form-check-input mb-4" ${include_in_report}>
    </div>`;
}

Append to table

function appendSignatureRequirement(record) {
  row = $('#signature_requirement_' + record['id']);
  texts = $('#signature_requirement_certificate_ids').select2('data');
  var html =
    '<td>' +
    non_null(record['signature_title']) +
    '</td>' +
    '<td>' +
    extractTextFromMultiSelect(texts) +
    '</td>' +
    '<td>' +
    extractMandatoryCheckbox() +
    '</td>' +
    '<td>' +
    extractShowInReportCheckbox() +
    '</td>' +
    '<td>' +
    "<a class='mr-2' href='javascript:editSignatureRequirement(" +
    record['id'] +
    ")'>" +
    "<i class='fa fa-pencil text-secondary' aria-hidden='true' data-toggle='tooltip' title='Edit'></i>" +
    '</a>' +
    "<a href='javascript:deleteSignatureRequirement(" +
    record['id'] +
    ")'>" +
    "<i class='fa fa-trash text-danger' aria-hidden='true' data-toggle='tooltip' title='Delete'></i>" +
    '</a>' +
    '</td>';
  if (!row.length) {
    row = $('#signature_requirements').append(
      "<tr id='signature_requirement_" + record['id'] + "'>" + html + '</tr>'
    );
  } else {
    row.empty();
    row.append(html);
  }
}

Create and insert into the database (extract checkbox values and then nullify on success)

$('#create-signature-requirement-btn').on('click', function(event) {
    event.preventDefault();

    let testMethodId = $('#test_method_id').val();
    let signatureTitle = $('#signature_title').val();
    let certificateIds = $('#signature_requirement_certificate_ids').val();
    let mandatory = $('input[name="mandatory"]').prop('checked') ? 1 : 0;
    let include_in_report = $('input[name="include_in_report"]').prop('checked')
      ? 1
      : 0;

    $.ajax({
      url:
        '/settings/test_methods/' + testMethodId + '/add_signature_requirement',
      dataType: 'json',
      method: 'POST',
      data: {
        signature_requirement: {
          signature_title: signatureTitle,
          certificate_ids: certificateIds,
          mandatory: mandatory,
          include_in_report: include_in_report
        }
      },
      success: function(data) {
        appendSignatureRequirement(data);
        $('#signature_title').val('');
        $('#signature_requirement_certificate_ids')
          .val(null)
          .trigger('change');
        // uncheck upon success
        $('#mandatory').prop('checked', false);
        $('#include_in_report').prop('checked', false);
      }
    });
  });

The table in Rails view

   .col-sm-10
      .table-responsive.mt-5
        %table.table.table-hover.table-valign-middle
          %thead
            %tr
              %th Title
              %th Certificate Types
              %th Mandatory
              %th Show in Report
              %th Actions
          %tbody#signature_requirements
            - @test_method.signature_requirements.each do |signature_requirement|
              %tr{:id => "signature_requirement_#{signature_requirement.id}"}
                %td
                  = signature_requirement.signature_title
                %td
                  - signature_requirement.certificates.each do |certificate|
                    %span.badge.badge-pill.badge-primary
                      = certificate.name
                %td
                  .form-check.text-center.mb-4
                    = check_box_tag 'mandatory', nil, signature_requirement.mandatory == 1, class: 'form-check-input'
                %td
                  .form-check.text-center.mb-4
                    = check_box_tag 'include_in_report', nil, signature_requirement.include_in_report == 1, class: 'form-check-input'
                %td
                  %a.mr-2{:href => "javascript:editSignatureRequirement(#{signature_requirement.id})"}
                    %i.fa.fa-pencil.text-secondary{"aria-hidden" => "true", "data-toggle"=>"tooltip", "title"=>"Edit"}
                  %a{:href => "javascript:deleteSignatureRequirement(#{signature_requirement.id})"}
                    %i.fa.fa-trash.text-danger{"aria-hidden" => "true", "data-toggle"=>"tooltip", "title"=>"Delete"}

Image after implementation

enter image description here

mayorsanmayor
  • 2,870
  • 4
  • 24
  • 44