0

In my blade view, I have rows of fields for each value in backend and at the end an empty text field.

@php $x = 1; @endphp
@foreach ($base_urls as $base_url)
    <div class="input-group mb-3">
        <div class="input-group-prepend"><span class="input-group-text">{{ $x }}</span></div>
        <input type="text" class="form-control" placeholder="Insert url or leave empty to delete" aria-label="Edit or remove url" name="base_url_{{ $base_url->ID }}" value="{{ $base_url->url }}" />
    </div>
    @php $x++; @endphp
@endforeach

<div class="input-group mb-3">
    <div class="input-group-prepend"><span class="input-group-text">{{ $x }}</span></div>
    <input type="text" class="form-control" placeholder="Add url" aria-label="Insert url" name="base_url_" />
</div>

When the user inputs something to the last empty field, I want another empty field to be generated, and so on. So I made a JS script called admin_panel.js that looks like this

$('#base_urls_body form div.input-group:last-of-type input').change(function(e){
    last_input_group = $('#base_urls_body form div.input-group:last-of-type');

    if( $(e.target).val() != '' ){
        last_input_group.after('<div class="input-group mb-3"><div class="input-group-prepend"><span class="input-group-text">'+field_count+'</span></div><input type="text" class="form-control" placeholder="Add url" aria-label="Insert url" name="base_url_" /></div>');
    }

});

enter image description here

The field is being generated correctly, but the selector form div.input-group:last-of-type input is only detecting the input that was generated on page load, not the one generated with javascript

enter image description here

This is how I include my JS file in Laravel blade view. Its pushed to a stack in app.blade.php, the stack is called at the bottom of the body close tag.

@push('admin_panel')
    <script src="{{ asset('js/admin_panel.js') }}" defer></script>
@endpush

Maybe since admin_panel.js is loaded after everything else it doesn't detect new changes? If I remove defer attr from the script tag, I can't use jQuery in my .js file. How can I fix this?

Zurupupz
  • 335
  • 2
  • 12
  • 1
    Change `$('#base_urls_body form div.input-group:last-of-type input').change` to `$(document).on("change", "'#base_urls_body form div.input-group:last-of-type input", function...` – freedomn-m Sep 13 '20 at 17:52
  • 1
    [Understanding Event Delegation](https://learn.jquery.com/events/event-delegation/) – charlietfl Sep 13 '20 at 18:16

0 Answers0