How to pass value from button ID to input on click?

How can I pass the ID of a button to a hidden input?

I have a foreach to list users and generate a delete button, I want to pass the button's ID to a hidden input inside a modal.

@foreach

<button type="button" id="{{$user->id}}" data-toggle="modal" data-target="#modal-delete" onclick="deleteUser();"> Delete </button>

@endforeach

Here is what I've tried but didn't work.

function deleteUser(id) {
  $('input[name=user_id_modal]').val(id);

  alert(id);
}

<input type="hidden" name="user_id_modal"> ^ button's id should go here.

Answers 1

  • You can pass the userId into the function and manipulate the hidden input's name value as follows:

    function deleteUser(id) {
    
      $("input[name='user_id_modal']").val(id);
      console.log("Input value set to: " + $("input[name='user_id_modal']").val());
      
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <button type="button" id="userId" onclick="deleteUser(this.id);"> Delete </button>
    
    <input type="hidden" name="user_id_modal">


Related Articles