johnny_s johnny_s - 4 months ago 30
Javascript Question

Jquery toggle input value and button class

I have a PHP page that loads a form with pre-populated values from a MySQL database. Users are able to edit the form and update it with their desired data, this works.

I would like to offer them the ability to toggle one of the fields if it's not applicable. By doing so, the field will be populated with the text 'N/A' and the button class should change to 'btn-warning'. When clicked again the 'N/A' should be removed and the previous data re-inserted - is this possible?

So far I have it sort of working... when the button is clicked the input is populated with 'N/A' and the class changes, however it doesn't toggle, i.e the previous data doesn't re-appear and the 'N/A' remains.

I have created a FIDDLE, any help is appreciated.



$(document).ready(function() {
$("#ipclear").click(function() {
$("#ip").val('N/A');
$(this).toggleClass('btn-default').toggleClass('btn-warning');
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet" />

<div class="input-group">
<input type="text" name='ip' id="ip" class='form-control' value="1.2.3.4">
<div class="input-group-btn">
<button type="button" class="btn btn-default" id="ipclear">Not Applicable</button>
</div>
</div>




Answer

Store the text in a variable before toggle and set it again during next click.

Here is a working example:

$(document).ready(function() {
  var toggleText = $("#ip").val();
  $("#ipclear").click(function() {
    if ($("#ip").val() != 'N/A') {
      toggleText = $("#ip").val();
      $("#ip").val('N/A');
    } else
      $("#ip").val(toggleText);
    $(this).toggleClass('btn-default').toggleClass('btn-warning');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet" />

<div class="input-group">
  <input type="text" name='ip' id="ip" class='form-control' value="1.2.3.4">
  <div class="input-group-btn">
    <button type="button" class="btn btn-default" id="ipclear">Not Applicable</button>
  </div>
</div>

Comments