guillaumepotier / Garlic.js

Automatically persist your forms' text and select field values locally, until the form is submitted.

Home Page:http://garlicjs.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Not working when input field filled in using jQuery

pienisieni opened this issue · comments

I have a simple function that monitors for 'change' in two dropdown fields, then multiplies both values to update an input field with the total. The two dropdown fields persist fine -- but the filled in input field data is lost.

As someone reported here. With Firefox you can refresh the page without loosing the data, but if you close the browser/open the page on another tab it will get lost. And Chrome loses the data on refresh.

<label>Group Size</label>
<select class="selectpicker group calculate" id="group" name="group" data-rule-required="true" title="Choose Group Size...">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

<label>Price</label>
<select class="selectpicker price calculate" id="price" name="price" data-rule-required="true" title="Choose Price...">
<option value="10">Option A: $10</option>
<option value="20">Option B: $20</option>
<option value="30">Option B: $30</option>
</select>

<label>Total Sum:</label>
<input name='total' id='total' disabled='true' data='' />
$('.calculate').change(function(){
    var group = parseInt($('.selectpicker.group').val());
    var price = parseInt($('.selectpicker.price').val());
    var total = group * price;
if(isNaN(total)){
  $('#total').val('');
} else{
  $('#total').val('$' + total);
}
});

An easy solution to this, is to run the same function both on change and window.load -- something like in the following example could be used in some cases.

<script>
$('.calculate').on('change', function() {
    var group = parseInt($('.selectpicker.group').val());
    var price = parseInt($('.selectpicker.price').val());
    var total = group * price;
if(isNaN(total)){
  $('#total').val('');
} else{
  $('#total').val('$' + total);
}
});

$(window).on("load", function(){
  $('.calculate').change();
});
</script>

Hi there,

If you plan doing some javascript, you'll have to manually Garlic persist. For example:

$('#yourinput').val('my value'); // not Garlic persisted
$('#yourinput').garlic('persist'); // persisted

Best