1

How can I use a javascript variable 'x' inside an @if of Laravel? I tried to do it inside an @if and outside. Outside, it works perfectly, but I really need to do an action based on this condition.

var x = document.getElementById("IdPrize").value;

var mySpan = document.createElement("span");
mySpan.innerHTML = "\
@foreach (\App\Prize::all() as $prize)\
    @if ($prize->id == "+x+")\
        <p>{{$prize->name}} is the choosen one!</p>\
    @endif\
@endforeach";

Is there an specific reason for me not getting the variable 'x' value inside @if and @foreach? What can be done for it to work?

If I do it like the code below, it works perfectly.

var x = document.getElementById("IdPrize").value;

var mySpan = document.createElement("span");
mySpan.innerHTML = "\
@foreach (\App\Prize::all() as $prize)\
        <p>"+x+"</p>\
@endforeach";

Thank you!

changsnl
  • 21
  • 1
  • 6
  • just do it in javascript: `if( {{$price->id}} == x ) { ... }`. I think it does not work because it's evaluated one time when you request the file from the server as php code, so it does not interact with javascript code. – Ahmed Nour Jamal El-Din Mar 02 '19 at 05:03

1 Answers1

-1
<script type="text/javascript">

var x = document.getElementById("IdPrize").value;

</script>

In Php script it return as a string so you need to conert yout foreach element id to string So concat with string,

@foreach (\App\Prize::all() as $prize)\
    @php $x = print( ' <script>document.writeln(x);</script> ' ); @endphp
    @if ($prize->id."" == $x)\
        <p>{{$prize->name}} is the choosen one!</p>\
    @endif\
@endforeach";
GhanuBha
  • 142
  • 7
  • Hey, this function 'print': print( ' ' ); isn't working for me. The javascript part in my page doesn't show anymore. If I remove it, the code doesn't work as I want, but the javascript part shows up. Is there any other way? Thank you. – changsnl Mar 02 '19 at 13:05
  • `$x = print( ' ' );` is utter nonsense. The return value of `print` is always `1`. You can't execute JavaScript in the browser and then return the result to the PHP program which generated the JavaScript on the server. – Quentin Mar 02 '19 at 13:09
  • Yes there is a bug and print always return 1. but echo return actual value of js variable. – GhanuBha Mar 05 '19 at 09:05