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?
>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>