0

I have an html element inside my blade file:

<input id="check_all" onclick="toggleCheckOrders('$orderFormObject', ' $count')" name="check_all" type="checkbox" value="1">

The onclick handler is assigned a javascript function toggleCheckOrders which accepts two parameters which are objects that were passed from the controller to the blade template. When I do this, it just treats them as strings inside the javascript function, it there a way to pass them while retaining their respective data types?

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
Vince Gonzales
  • 855
  • 3
  • 20
  • 39

4 Answers4

0

You should use:

<input id="check_all" onclick="toggleCheckOrders('{{ $orderFormObject }}', ' {{ $count }}')" name="check_all" type="checkbox" value="1">

In Blade you use {{ ... }} to echo variable value

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
0

Here's a little helper I wrote for myself:

I added this in my AppServiceProvider.php:

 Blade::directive('jsvar', function ($expression) {
     return "<?php echo json_encode($expression); ?>";
 });

This will allow you to do:

<input id="check_all" onclick="toggleCheckOrders(@jsvar($orderFormObject), @jsvar($count))" name="check_all" type="checkbox" value="1">

If you find yourself passing PHP variables to JavaScript often I highly recommend this approach.

apokryfos
  • 38,771
  • 9
  • 70
  • 114
0

you can simply do

<input id="check_all" onclick="toggleCheckOrders({{json_encode($orderFormObject)}}, {{ json_encode($count)}})" name="check_all" type="checkbox" value="1">

carefull that associative array will be casted as object in JavaScript

N69S
  • 16,110
  • 3
  • 22
  • 36
0

In HTML do as seen below:

<input id="check_all" onclick="jsFunction(`{{json_encode($orderFormObject)}}`, `{{ json_encode($count)}}`)" name="check_all" type="checkbox" value="1">

In javascript, do the following:

<script>
  function jsFunction(orderFormObject, count) {
      const orderFormObjectNew = JSON.parse(orderFormObject);

      console.log(orderFormObjectNew);
      console.log(count);
  }
</script>

I hope this will be helpful.

Harrison O
  • 1,119
  • 15
  • 20