Bw70316
Bw70316

Reputation: 37

Javascript/Laravel only First ID works for button

I am using laravel and am looping to display all my users with an edit button. I want to hide the user edit form with javascript and have it appear on click. This works for the first item in my array, but when I try to edit a second user, the button won't work. Is there a way to insert an id into the form directly with laravel? I know it's because id is being reiterated, but all I'm not sure how to fix that.

users.index

@extends('layouts.admin')


@section('content')



<div class="col-sm-8">
    <div class="panel">


        @if($users)
        @foreach($users as $user)

        <p>{!! $user->name !!}</p>
        <button class="btn btn-primary" id="edit-user"> Edit</button>
        <hr>
        <div class="edit-user">
        <h1>Edit Users</h1>

            {!! Form::open(['method'=>'POST', 'action'=>'AccountController@store']) !!}

                <div class="form-group">
                    {!! Form::label('name', 'Client Name:') !!}
                    {!! Form::text('name', null, ['class'=>'form-control']) !!}
                </div>
                    {{ csrf_field() }}

                <div class="form-group">
                    {!! Form::label('start_access_date', 'start:') !!}
                    {!! Form::text('start_access_date', null, ['class'=>'form-control']) !!}
                </div>
                    {{ csrf_field() }}


                    <div class="form-group">
                    {!! Form::label('end_access_date', 'end:') !!}
                    {!! Form::text('end_access_date', null, ['class'=>'form-control']) !!}
                </div>
                    {{ csrf_field() }}


                    {{ csrf_field() }}
                <div class="form-group">
                    {!! Form::submit('Edit Account', ['class'=>'btn btn-primary']) !!}
                </div>

            {!! Form::close() !!}


        </div>
 @endforeach
        @endif



            </div>
        </div>
    </div>
</div>

<script type="text/javascript">

    $('.date').datepicker({  

       format: 'mm-dd-yyyy'

     });  

</script>  
  <script>

    $(document).ready(function(){

//if you wish to keep both the divs hidden by default then dont forget to hide //them           
$(".edit-user").hide();



$("#edit-user").click(function(){
      $(".edit-user").toggle();

});

});



</script>
    @endsection

Upvotes: 0

Views: 160

Answers (1)

Mr.Thanks
Mr.Thanks

Reputation: 225

Maybe you should use

<button class="btn btn-primary" class="edit-user-btn" data-id="{!! $user->id !!}"> Edit</button>

instead of

<button class="btn btn-primary" id="edit-user"> Edit</button>

And Then javascript like this:

$(".edit-user-btn").click(function(){
  // here You might use id for your form label
  // var user_id = $(this).data("id");
  $(".edit-user").toggle();

});

Upvotes: 0

Related Questions