aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/pl/treksoft/kvision/form/CheckBoxInput.kt
blob: 44383629bc3b23f07bb25656fb0f89252def376b (plain)
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
67
68
69
70
71
72
73
74
75
76
77
78
package pl.treksoft.kvision.form

import com.github.snabbdom.VNode
import pl.treksoft.kvision.core.Widget
import pl.treksoft.kvision.snabbdom.StringBoolPair
import pl.treksoft.kvision.snabbdom.StringPair

open class CheckBoxInput(override var value: Boolean = false,
                         name: String? = null, disabled: Boolean = false, id: String? = null,
                         classes: Set<String> = setOf()) : Widget(classes), BoolFormField {

    init {
        this.id = id
    }

    @Suppress("LeakingThis")
    var startValue: Boolean = value
        set(value) {
            field = value
            this.value = value
            refresh()
        }
    var name: String? = name
        set(value) {
            field = value
            refresh()
        }
    override var disabled: Boolean = disabled
        set(value) {
            field = value
            refresh()
        }
    override var size: INPUTSIZE? = null
        set(value) {
            field = value
            refresh()
        }

    override fun render(): VNode {
        return kvh("input")
    }

    override fun getSnClass(): List<StringBoolPair> {
        val cl = super.getSnClass().toMutableList()
        size?.let {
            cl.add(it.className to true)
        }
        return cl
    }

    override fun getSnAttrs(): List<StringPair> {
        val sn = super.getSnAttrs().toMutableList()
        sn.add("type" to "checkbox")
        if (startValue) {
            sn.add("checked" to "true")
        }
        name?.let {
            sn.add("name" to it)
        }
        if (disabled) {
            sn.add("disabled" to "true")
        }
        return sn
    }

    override fun afterInsert(node: VNode) {
        this.getElementJQuery()?.on("change", { _, _ ->
            val v = getElementJQuery()?.prop("checked") as Boolean?
            value = (v == true)
            true
        })
        this.getElementJQuery()?.on("click", { _, _ ->
            val v = getElementJQuery()?.prop("checked") as Boolean?
            value = (v == true)
            true
        })
    }
}