Ways to stop the click event from being triggered in JQuery

There is a single toggle switch that, when clicked, switches ON and a popup with close and OK buttons appears. However, if the toggle is clicked again, it switches OFF and disappears. The specific requirement is that with every click where the toggle switches ON and the popup appears, the toggle should not switch OFF until the user clicks the close button within the popup.

http://jsfiddle.net/5rdbe08a/3/

<script>
        $(document).ready(function () {
            var status = 0;
            $(document).on('click', '#isImpliedDelete', function () {
                status++;
                console.log(status);
                var popup = document.getElementById("myPopup");
                popup.classList.toggle("show");
                if (status % 2 == 0) {
                    $("#submitBtn").prop('disabled', false);

                } else {
                    $("#submitBtn").prop('disabled', true);
                }
            });

            $("#isImpliedDelete").click(function () {
                $("#myPopup").show();
                if ($("#submitBtn").prop('disabled', false) == true) {
                    $("#myPopup").show();
                }
            });

            $("#ok").on('click', function () {
                $("#myPopup").hide()
                $("#submitBtn").prop('disabled', false);
            });

            $("#close").on('click', function () {
                if ($("#myPopup").show() == true) {
                    $("#myPopup").hide();
                }
                $("#isImpliedDelete").click();
                $("#submitBtn").prop('disabled', false);
                console.log("close");

            });
        });

Answer №1

When it comes to logic, the first step is to determine if the modal is currently visible. If it is not, the switch should trigger the modal to appear. However, if the modal is already visible, the switch should maintain its current state by using e.preventDefault();.

Check out this updated version of your fiddle: EDIT2: revised fiddle based on recent comments:

http://jsfiddle.net/5fb4xc0L/1/

One thing to note about your code: I noticed that you are employing the jquery hide function, yet you are also using distinct "show" and "hide" classes to visually toggle the modal's visibility. It is important to understand that you cannot use hide() to conceal the element and then rely on toggling the .show class to make it reappear. Check out this article for a detailed explanation: Here is an explanation

Answer №2

I am not sure of your exact requirements, but I was able to resolve your toggle issue. Take a look at the solution below:

$(document).ready(function(){
  $(document).on('click','#isImpliedDelete',function(){
    $(this).attr('disabled', true);
    $('#myPopup').addClass('show');
  })
  
  $(document).on('click','#ok',function(){
      $(this).parents('.popup').next('.input-group-prepend').find('input[type="checkbox"]').prop('checked', false);
      $('#myPopup').removeClass('show');
      $('#isImpliedDelete').removeAttr('disabled')
  })

})
/* Radio Switches */
        .switch {
            position: relative;
            display: inline-block;
            width: 60px;
            height: 34px;
        }

        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #3c3c3c;
            -webkit-transition: .4s;
            transition: .4s;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 26px;
            width: 26px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            -webkit-transition: .4s;
            transition: .4s;
        }

        input:checked+.slider {
            background-color: #00afaa;
        }

        input:focus+.slider {
            box-shadow: 0 0 1px #00afaa;
        }

        input:checked+.slider:before {
            -webkit-transform: translateX(26px);
            -ms-transform: translateX(26px);
            transform: translateX(26px);
        }

        /* Rounded sliders */
        .slider.round {
            border-radius: 34px;
        }

        .slider.round:before {
            border-radius: 50%;
        }

        /* Popup container - can be anything you want */
        .popup {

            position: relative;
            align-content: center;
            display: flex;
            align-items: center;

            display: inline-block;
            cursor: pointer;
            margin: 0 auto;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
        }


        /* The actual popup */
        .popup .popuptext {


            align-content: center;

            visibility: hidden;
            width: 396px;
            border-style: groove;

            background-color: #555;
            color: #fff;
            text-align: center;
            border-radius: 6px;
            padding: 5px 0;
            position: absolute;
            z-index: 10000;
            /* bottom: 25%; */
            top: -50px;
            left: 310px;
            /* margin-left: -180px; */


        }

        /* Popup arrow */
        .popup .popuptext::after {
            content: "";
            position: absolute;
            top: 100%;
            /* left: 50%; */
            margin-left: -80px;
            border-width: 5px;
            border-style: solid;
            border-color: #555 transparent transparent transparent;
        }

        /* Toggle this class - hide and show the popup visible */
        .popup .show {
            visibility: visible;
            -webkit-animation: fadeIn 1s;
            animation: fadeIn 1s;
        }

        .popup .hide {
            visibility: hidden;
            -webkit-animation: fadeIn 1s;
            animation: fadeIn 1s;
        }

        /* Add animation (fade in the popup) */
        @-webkit-keyframes fadeIn {
            from {
                opacity: 0;
            }

            to {
                opacity: 1;
            }
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }

            to {
                opacity: 1;
            }
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br> <br> <br>


    <div class="popup">
        <span class="popuptext" id="myPopup">Hello,How are you?
            <button id="ok">Ok</button>
            <button id="close">Close</button>
        </span>
    </div>
    <div class="input-group-prepend">
        <label class="switch">
            <input id="isImpliedDelete" name="isImpliedDelete" type="checkbox">
            <span class="slider round"></span>
        </label>
    </div>

    <br> <br> <br>

    <button class="btn btn-primary btn-block" type="submit" id="submitBtn" >
        <i class="fa fa-file-upload mr-2"></i> Button
    </button>

If you need any further modifications, feel free to leave a comment.

Answer №3

Implemented e.preventDefault() within a click function.

$('#<id>').on(click,function(e){ e.preventDefault(); //Perform the desired action });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could possibly be causing issues with this query to the database?

-Problem Still Unsolved- I am facing issues with calling a database, retrieving all the rows from a table and storing them in an array. I then try to pass this table as JSON data to my JavaScript and use it as parameters for a function. But when I run the ...

The Next.js component only appears after a page reload

Essentially, I have a nested component that is supposed to render with the parent component and it works fine when the server initially starts. However, the issue arises when switching back from another page – some of the nested components disappear. A ...

Ajax transmits an array of data to the server

My table contains dynamic data with input fields for each item. I need to send the input field values along with the item's ID to the backend. Encountered Issue When making an AJAX request, the data sent as an array is not coming out as expected. Cod ...

Using the v-for directive in Vue.js to loop through an array and display

Looking at the image provided, I am trying to access the content. I attempted to do so using element.comments.content, but it did not seem to work as expected. Here is the snippet of code: <div class="fil-actualites-container"> <div cl ...

How can I employ CSS files within a Node module that is compatible with Next?

I recently made the switch from Gatsby to Next and I'm still learning the ropes. When working with Gatsby, I had a Node module that served as my UI library across different projects. This module utilized a CSS module file (style.module.css) that coul ...

Emphasizing the importance of organizing asynchronous jQuery Ajax requests

In my code, I have 2 asynchronous jQuery ajax calls. These calls are executed consecutively from a JavaScript file. The first call is initiated when the page loads and typically takes about 60 seconds to complete. However, depending on user input, the seco ...

What is preventing the addition of links to the navigation bar when using a sticky navigation bar?

Currently, I am in the process of developing a blog website using Django. One of the features I have successfully implemented is a sticky navigation bar. However, I am facing a challenge with adding links to the menu on the navigation bar due to existing ...

Choose items in a particular order based on the class name of their category

How can I dynamically select and manipulate groups of elements? My intention is to select and modify the msgpvtstyleme elements, then select the msgpvtstyle elements separately and work with them as well. The ultimate goal is to apply classes to these grou ...

Utilize HTML5 localStorage functionality

I have a good understanding of utilizing HTML5 localStorage with methods like localStorage.getItem/setItem. However, I am currently trying to figure out the implementation for a dynamic page. Let me explain the scenario: On my dynamic page (myPage.jsp), ...

Tips for Aligning h5 Headings with Unordered Lists

My footer contains the following code: HTML: <div class="container"> <div class="row"> <div class="col-md-6"> <div class="pull-right"> <h5><u><i>Information</i></u> ...

Exploring the process of incorporating a JavaScript library into an Angular project

I've encountered this issue before and know there are various workarounds available. I often search online for front-end design code to enhance the user experience of my projects, such as carousels, animations, and more. However, most of these project ...

ES5 enables the extension of classes in React

This ES6 syntax works fine for me: import {Component} from 'react'; class A extends Component {} class B extends A { // I can redeclare some methods here } But how would one implement this using ES5? Like so: var React = require('reac ...

Creating crawlable AMP versions of Angular websites

Having an Angular website where I dynamically load object properties, I am creating separate AMP sites for each of these objects. Typically, I would link to the AMP site from the canonical site. However, the issue arises because the crawler cannot find the ...

Styling a div to wrap around an image

I'm working with an image element that has the style attribute set to style='width:40%;height:40%'. My goal is to add a div around this image that will automatically adjust its size to wrap around the image. However, when I try inserting the ...

Storing approximately 1 kilobyte of information throughout various pages

Is it feasible to store approximately 1kb of data while transitioning between two pages on the same domain using Javascript, Jquery (1.7), and Ajax? For instance, a user inputs data into a textbox on one page and then moves to another specific page. Can ...

The jQuery error message "e.nodeName is undefined" indicates a timeout issue

<script type="text/javascript"> var delayFunction = (function() { var timer = 0; return function(callback, ms) { clearTimeout(timer); timer = setTimeout(callback, ms); }; })(); $(function() { $('#act ...

Store input values in subordinate rows - DataTables

I am facing an issue with my responsive DataTable within a Form. The DataTables plugin generates child rows on smaller devices, which contain some Input controls, leading to two specific problems. The **First problem:** Values from hidden child rows are n ...

Tips for creating a div element with a header and scrollable section

Greetings! I am currently developing a code to manage a sprinkler system interface with a modern and visually appealing design. At the moment, I have two columns on the page, each containing boxes. Unfortunately, the alignment of these boxes is not as desi ...

What is the solution to the error message that states a bind message provides 4 parameters, while a prepared statement "" necessitates 5?

Is there a way to fix the issue where the bind message provides 4 parameters but the prepared statement "" requires 5? I've tried solutions from others who faced similar problems without success. (I've included all classes for better error unders ...

What is the best way to limit a user from inputting a year beyond 2018 into a textbox using

<label>Year</label> <asp:Textbox id="year" runat="server" placeholder="year"> Please make sure to only enter years up until 2018 in this textbox. Thank you. ...