Search code examples
javascripthtml.netasp.net-mvcevent-listener

JS function not getting hit when button clicked


I have a button and im trying to fire the function below on click of "Duplicate". Could you guide me through the right way?

Currently, when i click nothing happens! There is no response. I need to fire the function on click.

Thanks in advance

JS

$(document).on('click', '.js-duplicateRoom', function (e) {
            var hiddenInput = $(this).parent().find('input[name="roomId"]');
            var roomId = hiddenInput.data('id');
            var type = 'duplicate';

            $.ajax({
                type: "GET",
                url: "/management/hostaccommodation/AddRoom?roomId=" + roomId + '&type=' + type,
            }).done(function (result) {
                $('#addRoomResult').html(result);
                // Hide Add Room Button
                $('#addNewRoom').hide();
                $('#backToDetails').hide();
                $('#nextPropertyExtras').hide(); // Next button
            });
        });

HTML

<div class="modal fade" id="duplicateModal" tabindex="-1" role="dialog" aria-labelledby="duplicateModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="duplicateModalLabel">Confirm Duplicate</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Are you sure you would like to duplicate this Room?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" id="js-duplicateRoom" >Duplicate</button>
            </div>
        </div>
    </div>
</div>

Solution

  • The button is identified by an ID, not a class. So try this instead:

    $(document).on('click', '#js-duplicateRoom', function(e) {
      var hiddenInput = $(this).parent().find('input[name="roomId"]');
      var roomId = hiddenInput.data('id');
      var type = 'duplicate';
    
      $.ajax({
        type: "GET",
        url: "/management/hostaccommodation/AddRoom?roomId=" + roomId + '&type=' + type,
      }).done(function(result) {
        $('#addRoomResult').html(result); // Hide Add Room Button
        $('#addNewRoom').hide();
        $('#backToDetails').hide();
        $('#nextPropertyExtras').hide(); // Next button
      });
    });