Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel Blade Component onclick function

Is it possible on blade component to call a function from onclick, and change its variable value?

 public $rental = true;
    /**
     * Create a new component instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\Contracts\View\View|\Closure|string
     */
    public function render()
    {
        return view('components.product-rental');
    }
    public function toggleRental(){
        $this->rental = !$this->rental;
    }
    <div class="row">
        <div class="col col-md-6">
            <div class="form-check form-switch">
                <input class="form-check-input" name="rental" type="checkbox" @click="toggleRental()" id="rental" value="1" checked>
                <label class="form-check-label" for="rental">Rental</label>
            </div>
        </div>
    </div>
    {{$rental}}

Basically, what i want is when i CLICK a button, it will call the "toggleRental()" function from blade component and update the "$rental" variable. Is this possible?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think you should consider using Livewire instead.

It provides exactly this kind of features.

Otherwise you should implement an API endpoint and use Javascript to do so.

EDIT:

So you can use something like this:

    <div class="row">
        <div class="col col-md-6">
            <div class="form-check form-switch">
                <input class="form-check-input" name="rental" type="checkbox" data-rental="{{ $rental }}" onclick="toggleRental" id="rental" value="1" checked>
                <label class="form-check-label" for="rental">Rental</label>
            </div>
        </div>
    </div>
    {{$rental}}

<script>
document.addEventListener('DOMContentLoaded', (event) => {
    var rentalCheckBox = document.querySelector('#rental');
    rentalCheckBox.value = rentalCheckBox.getAttribute('data-rental');
    function toggleRental(){
        rentalCheckBox.value = !rentalCheckBox.value;
    } 
});
</script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading