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>'
You have multiple problem in your code.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With