Reputation: 4366
Im working with Boostrap 3 and Jquery and Im trying toggle the text inside a button with an boostrap icon span, but doesnt know how to do. This is what I tried:
The html code:
<button type='button' class='btn btn-success btn-md'>
<span class='glyphicon glyphicon-edit'></span> Edit</button>
Jquery code:
$(this).text(function(i, text){
return text === "<span class='glyphicon glyphicon-edit'></span> Close" ? "<span class='glyphicon glyphicon-edit'></span> Edit" : "<span class='glyphicon glyphicon-edit'></span> Close"
})
So...How could be this works?
1) An example with the toggle text button but keeping the same icon.
2) Another example with the toggle text button but toggle the icon class
Thanks.
Upvotes: 1
Views: 1713
Reputation: 42054
Instead of === you can use indexOf because:
$(this).text() === "↵ Edit"
Like you can see there is an extra char (newline) and you cannot rely on this.
The snippet with the jQuery.html is:
$('button').on('click', function(e) {
$(this).html(function(i, text){
return (text.indexOf("Close") != -1) ? "<span class='glyphicon glyphicon-edit'></span> Edit" : "<span class='glyphicon glyphicon-edit'></span> Close"
})
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<button type='button' class='btn btn-success btn-md'>
<span class='glyphicon glyphicon-edit'></span> Edit</button>
Or, in JS you may write:
this.childNodes[2].textContent = (this.childNodes[2].textContent.indexOf("Close") != -1) ?
' Edit' : ' Close';
The snippet:
$('button').on('click', function(e) {
this.childNodes[2].textContent = (this.childNodes[2].textContent.indexOf("Close") != -1) ? ' Edit' : ' Close';
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<button type='button' class='btn btn-success btn-md'>
<span class='glyphicon glyphicon-edit'></span> Edit</button>
Upvotes: 3
Reputation: 8420
How about this:
<button class="btn btn-primary toggle-text" data-toggle="collapse" href="#collapseExample">
<span class='glyphicon glyphicon-edit'></span><span>Edit</span><span class="hidden">Close</span>...
$('.hidden').removeClass('hidden').hide();
$('.toggle-text').click(function() {
$(this).find('span').each(function() { $(this).toggle(); });
});
Upvotes: 1
Reputation: 26444
You should use html()
instead of text()
$(this).html(function(i, text){
return text === "<span class='glyphicon glyphicon-edit'></span> Close" ? "<span class='glyphicon glyphicon-edit'></span> Edit" : "<span class='glyphicon glyphicon-edit'></span> Close"
})
Upvotes: 0