简体   繁体   中英

change text of button when i click it

change text of button when i click it. when i click on the button if it show make it hide .

  $(function () { if ($(".clickMe").text() == 'show') { $(".clickMe").text("hide") } else { $(".clickMe").text("show") } }); 
 <a href="#" class="clickMe">ShowDetials</a> 

Bind an event to it first, i meant a click event

$(".clickMe").click(function(){
  $(this).text($(this).text() == "show" ? "hide" : "show");
});

DEMO

Change your code to this

Html

<a href="#" class="clickMe">show</a>

Script

$(function () {
    $('.clickMe').click(function(){
        $(this).text($(this).text() == "show" ? "hide" : "show");
     });
});

Demo

It's better to apply some attribute (like class) to indicate state of button. Also, when you click on link, browser will follow it, prevent that (if needed effect). And your function is fired only once when everything is loaded, but not when clicking element. Bind click event to element:

 $(document).ready(function() { $(".btn").click(function(e) { e.preventDefault(); // prevent from following link. if ($(this).hasClass('active')) { $(this) .removeClass('active') .text('Show Details'); } else { $(this) .addClass('active') .text('Hide Details'); } }); }); 
 .btn { text-decoration: none; border: 1px solid green; padding: 5px 10px; font-weight: bold; color: #454545; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="http://example.com" class="btn">Show Details</a> 

All purpose function

HTML part

<button type="submit" onclick="changeText(this,'Checking.. Please wait...')">Login</button>

JS part

// function to change text
function changeText(ref,text){
   ref.innerHTML = text;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM