I'm trying to change the text of a span
when it is clicked depending on the current value it has.
If it is Open - then set value to Close.
If it is Close - then set value to Open.
$('.details_btn').click(function(){
if($(this).text('Open'){
$(this).html('Close');
}else{
$(this).html('Open');
}
});
I've got a fiddle of what I've been doing here:
http://jsfiddle.net/javacadabra/ch0u1xws/
However, it doesn't seem to ever go back from Close to Open and I'm not sure why. Could someone shed some light on this?
Many thanks
Your if
statement is a bit wrong. The .text()
takes a parameter to set the text, simply call it parameterless to return the current text. So:
if($(this).text('Open')){
Should be:
if($(this).text() == 'Open'){
The text() function either retrieves or set's the inner text of an element. So to test it's current value you should use:
if($(this).text() == "Open")
Instead of
if($(this).text('Open'))
Update to your fiddle: http://jsfiddle.net/ch0u1xws/2/
$(document).ready(function(){ $('.details_btn').click(function(){ if($(this).text() == 'Open'){ $(this).html('Close'); }else{ $(this).html('Open'); } }); });
To get the current value, don't provide any parameters to the .text()
function, as others have mentioned. But an alternative solution is to pass a function in to manipulate the current value, like this:
$(document).ready(function(){
$('.details_btn').click(function() {
$(this).text(function(i, text) {
return text == 'Open' ? 'Close' : 'Open';
});
});
});
$(document).ready(function(){ $('.details_btn').click(function() { $(this).text(function(i, text) { return text == 'Open' ? 'Close' : 'Open'; }); }); });
.details_btn{ background-color: red; color:white; padding:20px; text-transform:uppercase; font-family:calibri; font-weight:bold; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <span class="details_btn">Open</span>
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.