0

I am trying to pass a value I have for the data-id in a button to a modal form. My code is below:

Script:

<script type="text/javascript">  

       $(document).on("click", "open-exampleModal", function () {
             var myBookId = $(this).data('id');
             $(".modal-body #bookId").val($(this).data('id'));
        });
 </script>

Button to open modal:

<div class="grid-cell" >
       <span>
          <button type="button" id="btnShowModal" class="btn btn-link btn-square-md" data toggle="modal" data-target="#exampleModal" data-id="B1"></button>
      </span>
    </div>

Modal:

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>

      <div class="modal-body" id="modalbody">
        <p>some content</p>
        <input type="text" name="bookId" value=""/>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

When I click the button to open the modal it opens the modal successfully, however, it does not populate the input with the value from the data-id. I took the code from another answer from awhile back and wondering if something potentially has updated since then.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • Does this answer your question? [jQuery's .click - pass parameters to user function](https://stackoverflow.com/questions/3273350/jquerys-click-pass-parameters-to-user-function) – bcstryker May 08 '23 at 18:54

2 Answers2

0

This selector doesn't match any element in your HTML:

$(".modal-body #bookId")

So no value is populated:

$(".modal-body #bookId").val(123);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="modal-body" id="modalbody">
  <input type="text" name="bookId" value=""/>
</div>

But this one does:

$(".modal-body input[name='bookId']").val(123);

Example:

$(".modal-body input[name='bookId']").val(123);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="modal-body" id="modalbody">
  <input type="text" name="bookId" value=""/>
</div>
David
  • 208,112
  • 36
  • 198
  • 279
0

You are doing a mistake in script. Update the script:-

$(document).on("click", "#btnShowModal", function () {
     var myBookId = $(this).data('id');
     $(".modal-body #bookId").val($(this).data('id'));
 });

Hope it will be helpful.

Developer
  • 1,297
  • 1
  • 4
  • 15