I want to reveal the hint in the input box of simple_form. While the unit "area_unit" selection changes,the hints changes too, area_unit can choose square meter and square feet. For example: When area_unit select sq.m, surface_area displays the current value area_unit as sq.m , while the hint displays the value area_unit as sq.feet. vice versa.
the slim code:
.col-md-3.col-xs-6
= f.input :surface_area, label: "Surface Area" ,hint:""
.col-md-3.col-xs-6
= f.input :area_unit, collection: Property::AREA_UNIT_NAMES.map(&:reverse), include_blank: false
/ (in \u33A1)
When the area_unit changes,the value surface_area changes too.
switchUnit: ->
$(document).on 'change', '#property_area_unit', ->
areaInput = $('#property_surface_area')
if $(this).val() == 'sq_m'
area = Math.round(parseFloat(areaInput.val())*0.0929*100)/100
else
area = Math.round(parseFloat(areaInput.val())*10.7639*100)/100
areaInput.val(area)
But how to set the content the hints ?
You'll need to do it using Javascript, too. In principle, you can simply add it to the change
event. If you use the default simple_form form builder, then the hint field should be rendered as a <span>
next to the input field itself, i.e. you should see something like the following when opening the source of the page:
<div class="input string optional property_surface_area field_with_hint">
<label class="string optional" for="property_surface_area">Surface Area</label>
<input class="string optional" type="text" value="" name="property[surface_area]" id="property_surface_area" />
<span class="hint"></span>
</div>
So the task is to update the value of the hint span
in the change
event of the units selection. The following code does that:
switchUnit: ->
$(document).on 'change', '#property_area_unit', ->
areaInput = $('#property_surface_area')
areaHint = $('.property_area_unit span.hint')
if $(this).val() == 'sq_m'
area = Math.round(parseFloat(areaInput.val()) * 0.0929 * 100) / 100
areaInOtherUnits = Math.round(area * 10.7639 * 100) / 100
else
area = Math.round(parseFloat(areaInput.val()) * 10.7639 * 100) / 100
areaInOtherUnits = Math.round(area * 0.0929 * 100) / 100
areaInput.val(area)
areaHint.html('= ' + areaInOtherUnits + ($(this).val() == 'sq_m' ? ' sq feet' : ' sq m'))
The code above recalculates the area back to the other units (you could as well probably just use the original value from the property_surface_area
input, but the recalculation also rounds it) and sets the hint content to this value, including the other units. The selector for the hint is: "the wrapping div for the whole form line → the span with the 'hint' class".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With