Update array data when clicking outside input

Viewed 42

Cordial greetings I am developing a project in Laravel where I perform a data update in a table dynamically, this data is an array that is created by selecting an item and the function I perform is that when I click on the green button updates the data entered in the array.

enter image description here

But a requirement that they have asked me is that the green button is not there, that when entering the data in the input and clicking outside the input, it updates automatically. To update my data I do it this way, This is my table

<table class="table table-bordered">
   <tr>
      <th style="font-size: 11.7px;">Item</th>
      <th style="font-size: 11.7px;">Eliminar</th>
   </tr>
   @foreach ($cart as $servicio)
   <tr>
      <td style="font-size: 11.7px;">
         <input type="text" 
                class="form-con-lg" 
                value="{{$servicio->n_item}}" 
                id="servicio_{{$servicio->id}}">
         <a class="btn-update-item btn btn-success" 
            data-href="{{ route('servicio_update',$servicio->id)}}" 
            data-id="{{$servicio->id}}">
            <i class="fas fa-sync-alt"></i>
         </a>
      </td>
      <td>
         <a href="{{ route('coti_delete' ,$servicio->id )}}" class="btn btn-danger"><i class="fas fa-trash-alt"></i></a>
      </td>
   </tr>
   @endforeach
</table>

and this is my script where I pass the data to update my array

<script type="text/javascript">
    $(document).ready(function(){
        $(".btn-update-item").on('click', function(e){
            e.preventDefault();
            var id = $(this).data('id');
            var href = $(this).data('href');
            var n_item = $("#servicio_" + id).val();
            swal("Good job!", "You clicked the button!", "success");
            window.location.href = href  + "/" + n_item;
        });
    });
</script>

and my controller where I update my array

//UPADTE
    public function update(Servicios $servicios,$n_item){
        $cart = Session::get('cart');
        $cart[$servicios->id]->n_item = $n_item;
        Session::put('cart', $cart);
        return redirect()->route('coti_show');
    }

and my route

 Route::get('/servicios/update/{servicios}/{n_item?}', 'Admin\CotizacionController@update')->name('servicio_update');

I would like to know how I can do that when I enter the data in the input and click outside the input it is automatically updated, thank you for your help.

1 Answers

As Bravo said, a blur handler could be used, and would probably be the most straightforward. The other route would be to add a click handler to the window (or some encapsulating parent within which you want to check for clicks) and check that the Event.target.id (or some other property of your liking) does not match that of the input.

That being said, the blur handler is most likely the more straightforward solution, just presenting alternatives.

Related