I am trying to achieve something very simple but I can’t figure it out. I would like to disable an input field whenever a button is clicked, then re-enable it when the button is clicked again.
I’m surely making this overly difficult (new to JS).
My current code is here in this FIDDLE.
Any help is appreciated. An explanation of what I have been doing wrong would also be great as I’d like to learn 🙂
$(document).ready(function() {
var toggleText = $("#ip").val();
$("#ipclear").click(function() {
if ($("#ip").val() != 'N/A') {
toggleText = $("#ip").val();
$("#ip").val('N/A');
$("#ip").prop("disabled", false);
} else
$("#ip").val(toggleText);
$(this).toggleClass('btn-default').toggleClass('btn-warning');
$("#ip").prop("disabled", true);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.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" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>
4
Answers
Working fiddle
You’ve to add braces
{}
arround else statement code or just first line$("#ip").val(toggleText);
will be considered as else code :Note : you have to use
addClass()/removeClass();
instead oftoogleClass()
in your case.Hope this helps.
Try this :
You need to manage with ToggleClass().
On click button add one toggleclass on input and check this class condition for disabled.
Try this , its working