chii chii - 1 year ago 107
jQuery Question

Is there a way to use javascript variable inside larval blade template?

I will automatically create the rows of a table in jQuery . by clicking addRow button , function addRow() will do it like below:

function addRow(){

var rowCount = $("table tr").length - 1;
var row = '<tr><td><input name=“item[‘+ (rowCount+1) + ']" type="text" value="{{ old(‘item') }}”> @if ($errors->has(‘item’)){{ $errors->first(‘item’) }}@endif<td></tr>' ;



I will call this method 5 times and it will create 5 input areas which name are item1. item2, item3, item4, item5.

in server side ,I use Laravel 5.2 Form Request Validation to validate every input field.

But if the validation failed , the old input and error will not set to the correct input field because

I can’t put the javascript variable rowCount into "{{ old(‘item') }}” which is a blade template.
and the same is {{ $errors->first(‘item’) }}.

I tried to write like this

'value="{{ old('giftValue[' . $rowCount .']') }}">'

and this

'value="{{ old('giftValue[' + $rowCount +’]’) }}">'

but does’t work.

does anyone have a good idea to solve this problem ?

Answer Source

Thank you every one that answered my question, but no answer can solve the problem of both the Old Value and the validation Error.

Eventually, I write the JS code and I also write a server side code which is almost the same as the JS. As Mina Abadir said, I should not add server side code to JS.

if the validation failed, I only rendered the Oldvalue and the validation Error in the server side code , in this way ,the most difficult part is that I have to use \Validator::make to add every error to a variable($items[$key]['oldvalue'] and $items[$key]['error']), which will be displayed in the serverside code .

the server side code like :

@if(validation_failed) {

 <input name="item[{{ $key }}]" type="text" value="{{ $items[$key]['oldvalue'] }}">
   @if (!empty($items[$key]['error']))<p class="formTable_error">{{ $items[$key]['error'] }}</p>@endif


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download