Home > front end >  show modal based on button name
show modal based on button name

Time:11-03

I am new to javascript and want to open multiple different modals based on the button label or name.

I'm doing an ajax call which will then open a modal based on the button label / name.

If someone can point me in the right direction that would be great. Below is what I am currently using which works with one modal but does not cater to different modal ids. Any help will be greatly appreciated.

//form button script

<form action="https://test.com/testme.html" method="post" class="ajax">
<button class="item" id="test1" name="testing" value="1" data-toggle="tooltip" data-placement="top" type="submit" title="" data-original-title="test1">
</button>
</form>

//javascript
<script>
$(document).ready(function() {

$('form.ajax').on('submit', function(event) {
   event.preventDefault();
   var that = $(this),
   url = that.attr('action'),
   type = that.attr('method'),
   data = {};

   that.find('[name]').each(function(index, value) {
      var that = $(this),
      name = that.attr('name'),
      value = that.val();

      data[name] = value;
   });

   // AJAX request
         $.ajax({
         url: url,
         type: type,
         data: data,
         success: function(response){
   // Add response in Modal body
   $('.modal-body').html(response);

   // Display Modal
   $('#MyModal').modal('show');//want #MyModal to be var button id test1 so $('#test1').modal('show')
    }
});
});
});
</script>

CodePudding user response:

You can do something like :

    <form action="https://test.com/testme.html" method="post" class="ajax">
    <button class="item" id="test1" data-model-name="modal1" value="1" data-toggle="tooltip" data-placement="top" type="submit" title="" data-original-title="test1">
    </button>
    <button class="item" id="test2" data-model-name="modal2" value="2" data-toggle="tooltip" data-placement="top" type="submit" title="" data-original-title="test2">
    </button>
    </form>

In jquery :

    $('form.ajax').on('submit', function(event) { 
    event.preventDefault(); 
    let activeButton = $(document.activeElement).data('model-name'); 
    $(`#${activeButton}`).modal('show');
    }
  • Related