I have this Javascript and HTML
<div class="col-lg-12">
<button type="button" onclick="myFunction()" class="btn btn-block btn-success"><i class="fas fa-search"></i> View Result</button>
</div>
<div id="myDIV" style="display:none">
This is my DIV element.
</div>
<script type="text/javascript">
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
By default, myDiv div tag is hidden. Then when the button is clicked it becomes visible, when it's clicked again it hides the div.
But beyond this, what I want is that when the div tag is visible the button caption should be
Hide Result
and when the div tag is hidden, the button caption should be
View Result
How do I modify ny current code to achieve this?
Thanks
Just surround the button caption in a <span>
tag with an id:
<div class="col-lg-12">
<button type="button" onclick="myFunction()" class="btn btn-block btn-success">
<i class="fas fa-search"></i>
<span id="button-caption">View Result</span>
</button>
</div>
And update the caption at the same time as you update the div visibility:
function myFunction() {
var x = document.getElementById("myDIV");
var y = document.getElementById("button-caption");
if (x.style.display === "none") {
y.innerHTML = "Hide Results";
x.style.display = "block";
} else {
y.innerHTML = "Show Results";
x.style.display = "none";
}
}
First of all, give your button an ID.
<button id="myButton" type="button" onclick="myFunction()" class="btn btn-block btn-success"><i class="fas fa-search"></i> View Result</button>
After that, in myFunction()
, simply apply document.getElementById("myButton").innerHTML = "New caption here"
wherever you want to change the caption.
You can change the textContent of the button when you show/hide the div
function myFunction() { var x = document.getElementById("myDIV"); var y = document.getElementById("btn"); if (x.style.display === "none") { x.style.display = "block"; y.textContent = "Hide Result"; } else { x.style.display = "none"; y.textContent = "View Result"; } }
<div class="col-lg-12"> <button id="btn" type="button" onclick="myFunction()" class="btn btn-block btn-success"><i class="fas fa-search"></i> View Result</button> </div> <div id="myDIV" style="display:none"> This is my DIV element. </div>
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.