Toggle text on button tag
I have a show hide table rows feature but would now like to change my text.
<script language="javascript" type="text/javascript">
function HideStuff(thisname) {
tr = document.getElementsByTagName('tr');
for (i = 0; i < tr.length; i++) {
if (tr[i].getAttribute('classname') == 'display:none;') {
if (tr[i].style.display == 'none' || tr[i].style.display=='block' ) {
tr[i].style.display = '';
}
else {
tr[i]开发者_高级运维.style.display = 'block';
}
}
}
}
The html is as follows...
<button id="ShowHide" onclick="HideStuff('hide');>Show/Hide</button>
I want to toggle the "Show/Hide" text. Any ideas?
$('#HideShow').click(function()
{
if ($(this).text() == "Show")
{
$(this).text("Hide");
}
else
{
$(this).text("Show");
};
});
Alternative, the .toggle() has an .toggle(even,odd); functionality, use which ever makes most sense to you, one is slightly shorter code but perhaps less definitive.
$('#HideShow').toggle(function()
{
$(this).text("Hide");
HideClick('hide');
},
function()
{
$(this).text("Show");
HideClick('hide');
}
);
NOTE: you can include any other actions you want in the function() as needed, and you can eliminate the onclick in the markup/html by calling your HideClick() function call in there. as I demonstrate in the second example.
As a follow-up, and to present an alternative, you could add CSS class to your CSS
.hideStuff
{
display:none;
}
THEN add this in:
.toggle('.hideStuff');
or, more directly:in the appropriate place.
.addClass('.hideStuff');
.removeClass('.hideStuff');
Use jQuery something like this might work:
$('ShowHide').click(function(){
if ( $('hide').css('display') == 'block' )
$('ShowHide').val("Hide");
else
$('ShowHide').val("Show");
});
I just wrote that from the top of my head though, so you might need to do some changes, you can read more about the css jquery api here. And all I did was using anonymous functions
I would recommend using jquery but you can just use javascript's document.getElementById
method
in your function:
function HideStuff(thisname) {
tr = document.getElementsByTagName('tr');
for (i = 0; i < tr.length; i++) {
if (tr[i].getAttribute('classname') == 'display:none;') {
if (tr[i].style.display == 'none' || tr[i].style.display == 'block') {
tr[i].style.display = 'none';
}
else {
tr[i].style.display = 'block';
}
}
}
if (document.getElementById("ShowHide").value == "show") {
document.getElementById("ShowHide").value = "hide";
}
else {
document.getElementById("ShowHide").value = "show";
}
}
Although, I would probably pass in this
instead of the text 'hide' in the function call. then yon can do it like zaph0d stated. Its a bit cleaner then.
Not sure why you are passing thisname into the JS as this is not currently getting used.
If you change the call to:
<button id="ShowHide" onclick="HideStuff(this)">Show</button>
and then in the js you can change the text fairly easily:
if (this.value == 'Show') {
this.value = 'Hide'
}
else {
this.value = 'Show';
}
精彩评论