April 18, 2011

jquery toggle button value

Question by Rajeev

In the below code when the play button is clicked Its value should be changed to pause and when pause is clicked the other function should be called .How to do this using jquery toggle

  <input type="button" onclick ="play" value="play"/>
   <script>
     function play()
     {
               play_int();
           //   Button value to be changed to pause
     }   

  And when pause play_pause();

Answer by Town

Give your button an ID:

<input type="button" id="play" value="play"/>

Then you can do something like this:

$('#play').click(function() {
   if ($(this).val() == "play") {
      $(this).val("pause");
      play_int();
   }
   else {
      $(this).val("play");
     play_pause();
   }
});

Or a slightly tidier version like this:

$(function(){
    $('#play').click(function() {
       // if the play button value is 'play', call the play function
       // otherwise call the pause function
       $(this).val() == "play" ? play_int() : play_pause();
    });
});

function play_int() {
    $('#play').val("pause");
    // do play
}

function play_pause() {
    $('#play').val("play");
    // do pause
}

Working demo

Answer by Starx

A simplest idea can be this

function play(action) {
 { 
   if(action=='play') { 
      play_int(); 
      $("#btn_play").val('pause');
   }
   else { 
      pause_int(); 
      $("#btn_play").val('play');
   }
}

$("#btn_play").click(function() {
   val = $(this).val();
   play(val);
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!