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>
3
Answers
You need to assign your text value in a variable and reassign after toggle.
Store the text in a variable before toggle and set it again during next click.
Here is a working example:
You are not restoring the value of the input field in your code. Somewhere you need to remember the old value and restore it on second click.
I updated your JSFIDDLE with a possible solution:
https://jsfiddle.net/Doogie/6pqugkg3/5/
Some more tips:
If you have more than one field, then you need to remember the original value of each of them. One way you could do that is via data- attributes on the input elemnts:
<input value="currentValue" data-orig="originalValueFromDB" id="ip" ....>
You can get the original value with JQuery just as any other attribute:
var origValue = $('#ip').attr('data-orig'); // origValue = "originalValueFromDB'