-2

I have a button in html

<input id="LockUnlock"
       type="submit" 
       class="btn-sm btn-primary" 
       value="@(agent.IsLockedOut ? "Unlock" : "Lock")"/>

It correctly sets the value based on the model but I want to toggle the button text when I click it.

My Javascript:

<script type="text/javascript">
        $('input[type = submit]').click(function () {
            if ($(this).text() === "Lock") 
            { 
                $(this).text("Unlock"); 
            } 
            else 
            { 
                $(this).text("Lock"); 
            }
        });
    </script>

Nothing happens when I click the button. I'm not seeing errors in the console window in Chrome.

Stuart
  • 3,720
  • 4
  • 24
  • 50

2 Answers2

1

Use $(this).val() instead $(this).text().

Also, I fixed some code errors that you had in your question.

 $('input[type=submit]').click(function () {
            if ($(this).val() === "Lock") 
            { 
                $(this).val("Unlock"); 
            } 
            else 
            { 
                $(this).val("Lock"); 
            }; 
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="LockUnlock"
       type="submit" 
       class="btn-sm btn-primary" 
       value="Unlock"/>

Note: Check out this post to learn the differences between .text() and .val()

Ricardo Rocha
  • 8,628
  • 9
  • 53
  • 91
0

You can write this <input id="LockUnlock" type="submit" class="btn-sm btn-primary" value="@(agent.IsLockedOut ? 'Unlock' : 'Lock')"/>

Jinesh
  • 1,536
  • 10
  • 15