HTML and JavaScript: Change button text (Toggle)

1069 views javascript
3

I need to change a button's text, however I think the issue I don't understand is how to change it back using separate files. I need to use jQuery to toggle pictures. This will hide the image and show the image. The button is "hard coded" I think in both the HTML and JavaScript.

The button is showing "hide" to initially hide the image. Once the button is clicked the image disappears and the button's text turns to "Show". However it will not turn back to "hide".

HTML:

<img src="sky.jpg" id="sky">
<input type='button' onclick="js/toggle.js" id="skybutton" value="Hide">

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/toggle.js"></script>

JavaScript:

$('#skybutton').click(function() {
    $("#sky").toggle();
    $(skybutton).val('Show');
});

answered question

have you tried adding a conditional to check the name of the label ?

2 Answers

9

Welcome to stackoverflow Shepard!!

You need little bit of logic in your javascript in order to make this work both ways:

<img src="sky.jpg" id="sky">
<input type='button' onclick="js/toggle.js" id="skybutton" value="Hide">

Here in the click function is where you need magic to happen: Try this code:

$('#skybutton').click(function() {
    $("#sky").toggle();
    if($(this).value() === 'Hide'){
        $(this).value('Show');
    }else{
        $(this).value('Hide');
    }
});

So what is happening above is that you already have a click function attached to the button so with in the function you can refer to that button as this and you can check what the value of the button is.

Your if statement goes hey button if your value is 'Hide' change the value to 'Show' and else your value must be 'Show' so change it back to 'Hide' let me know if I can clear anything else up for you. Good luck with the project

posted this
3

You can achieve this using an if else statement say:

 $('#skybutton').click(function() {
         If($(this).Val()=="hide"){
           $("#sky").hide();
            $(this).Val("Show")
    }else{      
              $("#sky").show();
                 $(this).Val("hide")
          }

});

posted this

Have an answer?

JD

Please login first before posting an answer.