Matthew Phelan
3 years ago
14 changed files with 206 additions and 136 deletions
@ -0,0 +1,12 @@
|
||||
module NumericQuestionsHelper |
||||
def numeric_question_html_attributes(question) |
||||
return {} if question["fields-to-add"].blank? || question["result-field"].blank? |
||||
|
||||
{ |
||||
"data-controller": "numeric-question", |
||||
"data-action": "numeric-question#calculateFields", |
||||
"data-target": "#{question['result-field'].to_s.dasherize}-field", |
||||
"data-calculated": question["fields-to-add"].to_json, |
||||
} |
||||
end |
||||
end |
@ -0,0 +1,12 @@
|
||||
import { Controller } from "@hotwired/stimulus" |
||||
|
||||
export default class extends Controller { |
||||
calculateFields() { |
||||
const affectedField = this.element.dataset.target; |
||||
const fieldsToAdd = JSON.parse(this.element.dataset.calculated).map(x => `${x.replaceAll("_","-")}-field`); |
||||
const valuesToAdd = fieldsToAdd.map(x => document.getElementById(x).value).filter(x => x); |
||||
const newValue = valuesToAdd.map(x => parseInt(x)).reduce((a, b) => a + b, 0); |
||||
const elementToUpdate = document.getElementById(affectedField); |
||||
elementToUpdate.value = newValue; |
||||
} |
||||
} |
@ -1,5 +1,7 @@
|
||||
<%= f.govuk_number_field question_key, |
||||
hint: { text: question["hint_text"] }, |
||||
label: { text: question["header"].html_safe, size: "l"}, |
||||
min: question["min"], max: question["max"], step: question["step"], width: 20 |
||||
min: question["min"], max: question["max"], step: question["step"], |
||||
width: 20, :readonly => question["readonly"], |
||||
**numeric_question_html_attributes(question) |
||||
%> |
||||
|
@ -0,0 +1,21 @@
|
||||
require "rails_helper" |
||||
|
||||
RSpec.describe NumericQuestionsHelper do |
||||
let(:form) { Form.new(2021, 2022) } |
||||
let(:questions) { form.questions_for_page("rent") } |
||||
|
||||
describe "html attributes" do |
||||
it "returns empty hash if fields-to-add or result-field are empty " do |
||||
expect(numeric_question_html_attributes(questions["total_charge"])).to eq({}) |
||||
end |
||||
|
||||
it "returns html attributes if fields-to-add or result-field are not empty " do |
||||
expect(numeric_question_html_attributes(questions["basic_rent"])).to eq({ |
||||
"data-controller": "numeric-question", |
||||
"data-action": "numeric-question#calculateFields", |
||||
"data-target": "#{questions['basic_rent']['result-field'].to_s.dasherize}-field", |
||||
"data-calculated": questions["basic_rent"]["fields-to-add"].to_json, |
||||
}) |
||||
end |
||||
end |
||||
end |
Loading…
Reference in new issue