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 >
<div >
<div >
<input name="rental" type="checkbox" @click="toggleRental()" id="rental" value="1" checked>
<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?
CodePudding user response:
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 >
<div >
<div >
<input name="rental" type="checkbox" data-rental="{{ $rental }}" onclick="toggleRental" id="rental" value="1" checked>
<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>