Home > database >  Laravel syntax within the element generated by jquery
Laravel syntax within the element generated by jquery

Time:01-08

I am trying to add some HTML elements with jquery. My effort might useless. My purpose is to generate select options within the page dynamically as in below. I know that I can list down options with laravel, but if I generate the select options with jquery can I insert laravel syntaxes within the code generated by jquery as in below.

'<div >'  
   '<select name="method_body" id="method_body"  required>'  
       '<option disabled selected>Select Method Body</option>'  
       '<option value="">ASTM</option>'  
       '<option value="">Jacobi</option>'  
       '<option value="">JIS</option>'  
    '</select>'  
'</div>' 

If I develop that select option with laravel within the html will be like below.

<div >
  <select name="method_body" id="method_body"  required>
      <option disabled selected>Select Method Body...</option>
      @foreach ($methodBodys as $methodBody)
         <option value="{{ $methodBody->id }}">{{ $methodBody->method_body }}</option>
      @endforeach
   </select>
</div>

My problem is, can I insert the above foreach loop element generated by jquery? As in below,

'<div >'  
   '<select name="method_body" id="method_body"  required>'  
      '<option disabled selected>Select Method Body...</option>' 
      '@foreach ($methodBodys as $methodBody)' 
          '<option value="{{ $methodBody->id }}">{{ $methodBody->method_body }}</option>' 
      '@endforeach' 
    '</select>'  
'</div>'  

But if I add laravel inside the element generated, it will only display

{{ $methodBody->method_body }}

as an options in select. If there is another way of doing this, how? please help me with the problem.

CodePudding user response:

PHP operates on the server side, before any data is passed to the client. Added to that, Blade is a proprietary templating language that is processed by Laravel before being rendered as PHP. JavaScript happens entirely in the user's browser.

However, you can pass values from Laravel to your JavaScript as a variable, for the client-side code to manipulate as needed. Use the @json Blade directive to make PHP variables safely available for use in your script:

const methodBodies = @json($methodBodys);
var html = `<div >
<select name="method_body" id="method_body"  required>
<option disabled selected>Select Method Body...</option>`;
for (const methodBody of methodBodies) {
    html  = `<option value="${methodBody.id}">${methodBody.method_body}</option>`;
}
html  = '</select></div>';
  •  Tags:  
  • Related