0

Having this checkbox in a form(+ a textarea)

<save-numbers id="save-numbers" inline-template>
    <div>
        <label class="inline-block text-gray-500 font-bold mb-4">
            <input class="mr-2 leading-tight" type="checkbox" name="saveNumbers" id="saveNumbers" v-model="toggle" {{ old('saveNumbers') ? 'checked' : '' }}/>
        </label>
        <div>
            <textarea 
            :class="{ hidden: !toggle }"
            class="w-full bg-gray-200 text-gray-700 border @error('notes') border-red-500 @enderror rounded py-3 px-4 mb-3 focus:outline-none focus:bg-white" 
            name="notes" id="notes" cols="30" rows="1" 
            placeholder="Add some notes">{{ old('notes', $validatedData['notes'] ?? '') }}</textarea>
        </div>
    </div>
</save-numbers>

How do I initialize/update the data on page load on form validation failure, so that the checkbox is checked? By default is not checked but if the form fails and the box was checked the checked attribute is not set in the VueJs component.

Here's the VueJs code

if (document.getElementById("save-numbers")) {
    Vue.component('save-numbers', {
        mounted: () => {

        },
        data() {
            return {
                title: 'Check me',
                toggle: false,
            }
        },
        methods: {
        },
    });

    new Vue({ el: '#save-numbers' })
}

I want to detect if the checked attribute is set and update the toggle accordingly.

Thank you

orbitory
  • 1,090
  • 5
  • 16
  • 40
  • Initialise `toggle` with the appropriate value – Phil Jun 09 '20 at 22:54
  • I am not sure how to do that. Do you have a link to the docs? – orbitory Jun 10 '20 at 00:08
  • Does this answer your question? [How to pass a PHP variable to Vue component instance in Laravel blade?](https://stackoverflow.com/questions/41520258/how-to-pass-a-php-variable-to-vue-component-instance-in-laravel-blade) – Phil Jun 10 '20 at 00:10
  • It might, props could work, I was hoping for a better way, directly from the checkbox field. maybe even using :checked – orbitory Jun 10 '20 at 00:14

2 Answers2

0

In the end I used plain js to get the checked status of the checkbox at page load but would like to have more "vuesc" way to do that.

Vue.component('save-numbers', {
        data() {
            return {
                toggleNotes: document.getElementById('saveNumbers').checked,
            }
        },
        methods: {
        },
    });
orbitory
  • 1,090
  • 5
  • 16
  • 40
0
data() {
    return {
        title: 'Check me',
        toggle: false,
        isChecked: true,
    }
},

return a boolean

 <label class="inline-block text-gray-500 font-bold mb-4">
            <input class="mr-2 leading-tight" type="checkbox" name="saveNumbers" id="saveNumbers" v-model="toggle" {{ old('saveNumbers') ? 'checked' : '' }}/>
       checked="isChecked" </label>
Ray Lee
  • 34
  • 4