views:

98

answers:

5

I have a toggle button, with a show/hide feature in javascript. How do I change the text when the button is clicked?

<button id="ShowHide">Show</button>
A: 

You'll have to use Javascript. Either hard code the new value in the Javascript or use AJAX to call back to the server and get the new value.

If you're just going to hard code the value in your Javascript...jQuery makes it a snap:

('#yourButton').click(function(){
    (this).text('Hello click!');
});
Justin Niessner
+4  A: 

Using jQuery:

$('#ShowHide').toggle(
    function() { 
        $(this).text("Show");
        $('whatever').show();
    },
    function() { 
        $(this).text("Hide");
        $('whatever').hide();
    }
);
SLaks
Made and update... I should have given more information. Not sure what "whatever" is
`'whatever'` is a jQuery selector for the element(s) that you want to hide. http://api.jquery.com/category/selectors/
SLaks
+1  A: 

You can use this jquery to do the change.

$("#buttonName").val("New text for button"); 

JQuery is automatically included in your ASP.NET MVC Project.

C. Ross
A: 

In pure HTML/JS:

<input type="button" id="show_hide" onclick="this.value=(this.value=='Show')?('Hide'):('Show')" value="Show" />
Dolph
Whoops, just saw the update asking for jQuery. Maybe this will be useful to someone else.
Dolph
A: 
$('#HideShow').click(function()
{
  if ($(this).text() == "Show")
  {
     $(this).text("Hide");
  }
  else
  {
     $(this).text("Show");
  };
});

EDIT: Updated to use the new valid ID which should be faster :) Brain cramp: cannot remember if it is .val() or .text() on the "button" tag as opposed to the <input type="button"> tag, no time to test atm but you get the idea (and I think I have it right:) ).

Alternative, the .toggle() has an .toggle(even,odd); functionality.

$('#HideShow').toggle(function() 
  { 
   $(this).text("Hide"); 
  }, 
  function() 
  { 
     $(this).text("Show"); 
  } 
); 
Mark Schultheiss