All files form.js

25% Statements 4/16
0% Branches 0/4
20% Functions 2/10
26.67% Lines 4/15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66        2x 2x               1x 1x                                                                                                      
import $ from 'jquery'
 
class Form {
  constructor(rules, prefix) {
    this.rules = rules
    this.prefix = prefix
  }
 
  // A Form matches the Form instance in Django, has a jQuery form object, a
  // prefix and rules.
  //
  // Update the form on instanciation to start with a clean state.
  bind(form) {
    this.form = $(form)
    form.on('change', ':input', $.proxy(this.update, this))
  }
 
  // Return the jQuery field instance for a field name.
  fieldGet(field) {
    let prefix = this.prefix ? this.prefix : ''
    return this.form.find(':input[name=' + prefix + field + ']')
  }
 
  // Return the jQuery field label instance for a field name.
  fieldLabelGet(field) {
    return $('label[for=' + this.fieldGet(field).attr('id') + ']')
  }
 
  // Return the jQuery field container for a field name, it's the element that
  // contains both the field and label.
  fieldContainerGet(field) {
    return this.fieldGet(field).parents().has(this.fieldLabelGet(field)).first()
  }
 
  // Return the value of a field by name.
  fieldValueGet(field) {
    return this.fieldGet(field).val()
  }
 
  // Clear the value of a field by name.
  fieldValueClear(field) {
    return this.fieldGet(field).val('')
  }
 
  // Hide a field container.
  fieldHide(field) {
    return this.fieldContainerGet(field).hide()
  }
 
  // Show a field container.
  fieldShow(field) {
    return this.fieldContainerGet(field).show()
  }
 
  // Update the UI.
  update() {
    if (ddf.debug) console.log('[Form] ', this, '.update()')
 
    for (var i=0; i<this.rules.length; i++) {
      this.rules[i].apply(this)
    }
  }
}
 
export { Form }