skip to Main Content

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.

2

Answers


  1. 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>
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search