简体   繁体   中英

how to change value of a button on click

I am trying to change the value of a button when onclick. so far I am able to get that working but i would like it to change back to the original value when click again. any suggestions?

my code:

{if $activity_count > "0"}
<input onclick="change()" type="button" class="rbutton" value="Show/Hide" id="show_act" />

{literal}
  <script>
   function change()
 {
  document.getElementById("show_act").value="Hide/Show"; 

}
 </script>
{/literal}

{else}
      {/if}

Set a flag:

var state = true;

Then modify your change function to toggle the state and do the appropriate update based on the state:

function change()
{
  var textValue = state ? "Hide/Show" : "Show/Hide";   // select the value based on the state
  document.getElementById("show_act").value=textValue; // apply the value
  state = !state;                                      // toggle the state for the next click
}

Here is a live example: http://jsfiddle.net/7kxA8/

Try this:

document.getElementById("show_act").value = (document.getElementById("show_act").value == "Show") ? "Hide" : "Show";

This one line code is enough within change() function.

Here is an example that will have a button that says hello and goodbye when it is clicked. The variable is a bit challenging to call with the variable as document.getElementById("show_act"). In this case, the submit button has an ID called "show_act" so be sure you keep track of what you name it. Good luck in your programming!

<script>
function change(id,text1,text2){
    if(document.getElementById(id).value == text1) document.getElementById(id).value = text2;
    else document.getElementById(id).value = text1;
}
</script>
<input onClick="change('show_act','Show','Hide');" type="button" class="rbutton" value="Show" id="show_act" />

You can try this:-

function change()
{
var element = getdocument.ElemnetById .("show_act");
 element.setAttribute("clicked",true);
if(element.getAttribute("clicked") === 'true'){
element.value="Show/Hide"; 
element.removeAttribute("clicked")
}else {
element.value="Hide/Show"; 
}
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM