简体   繁体   中英

Show modal on click using AJAX and JavaScript

Having an issue showing a modal window after I have parsed the JSON and placed the values into a TABLE TR.

 $('#serviceload').change(function()  // on dropdown select change
 {
   var page = $('#serviceload').val();  // dropdown selection set to page
   if(page == "")
   {
     $('#completeProfile').hide();  // if page is blank, hide content
   }
   else
   {
     $.post('api/vesselSearch.php', {page: page}, function(data)
     {
       var obj = JSON.parse(data); // parse the data
       $('#vesselinfo').empty(); // clear previous vessel content
       var htmlToInsert = obj.map(function (item)
       {
         return '<tr><td><a href="#" id="editVesselLink" data-toggle="modal" data-vessel="'+item.VESSEL_NAME+'">Edit</a></td><td>'+item.VESSEL_NAME+'</td></tr>';
       });
       $('#vesselinfo').html(htmlToInsert); // insert new vessel content
     });
   $('#completeProfile').show(); // show all content on page
   }
 });

As you will see above, after the JSON is parsed, I display the values in a TABLE row, which may have more than 1 row. The first TD cell contains a hyperlink which should open my edit modal.

The code to transfer the data from the row and display it in the modal looks like this:

 $('#editVesselLink').click(function(e)
 { 
   e.preventDefault();
   $('#editVesselForm input').val(''); // clear previous values
   $vessel= $(this).attr('data-vessel'); 
   $('#editvesselname').val($vessel);
   $('#editVesselInfoModal').modal('show');  // show the modal
 });

Here is where my problem begins.

I am not sure where to place the code directly above. I have placed it inside the $.post beneath $('#vesselinfo').html(htmlToInsert); , and that was the only place I could get the modal to even open, but only for the first record.

Basically, I can only get the modal to open for the first record when I place the second piece of code inside the $.post . The modal will not open at all in any other place that I put the code.

I tried to use a $(document).ready(function{}); to no avail.

What am I missing?

Ok, I think that the problem is on:

...
return '<tr><td><a href="#" id="editVesselLink" data-toggle="modal" data-vessel="'+item.VESSEL_NAME+'">Edit</a></td><td>'+item.VESSEL_NAME+'</td></tr>';
...
  • You can not repeat id property on the code, so, where is id="editVesselLink" put class="editVesselLink" and on $('#editVesselLink') put $('.editVesselLink')

why did it happens?

  • By HTML convection's the id have to be unique on HTML, so jQuery expects to recover only one element with that id, by default jQuery recover the first with that id if it is duplicated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM