Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a toggle button using jQuery

Tags:

jquery

button

I am trying to toggle a button using below code.

import $ from "jquery";

$(".clickMe").click(function() {
  $(this).text(function(i, text) {
    return text === "ON" ? "OFF" : "ON";
  })
});

const rootApp = document.getElementById("root");
rootApp.innerHTML = '<button class="clickMe">ON </button>'
like image 601
Arvind Singh Avatar asked Jul 04 '26 10:07

Arvind Singh


1 Answers

You have multiple problem in your code.

  1. Dynamic created markup need delegated event handlers.
  2. You have extra space on button text. You need to trim() text to avoid extra space before proceed.

Example:

$(document).on('click', '.clickMe', function() {
  $(this).text(function(i, text) {
    var txt = text.trim();
    return txt === "ON" ? "OFF" : "ON";
  })
});
const rootApp = document.getElementById("root");
rootApp.innerHTML = '<button class="clickMe">ON </button>'
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="root"></div>

Or only jQuery Version:

const rootApp = $('#root');
var html = `<button class="clickMe">ON </button>`; // Declare your button
rootApp.append(html); // Append your HTML on desire element

$(document).on('click', '.clickMe', function() {
  $(this).text(function(i, text) {
    var txt = text.trim();
    return txt === "ON" ? "OFF" : "ON";
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="root"></div>
like image 120
4b0 Avatar answered Jul 06 '26 02:07

4b0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!