johnny_s johnny_s - 4 months ago 17
jQuery Question

Toggle input on button click

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>




Answer

Working fiddle

You've to add braces {} arround else statement code or just first line $("#ip").val(toggleText); will be considered as else code :

$(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", true);
            $(this).removeClass('btn-default').addClass('btn-warning');
        } else{
            $("#ip").val(toggleText);
            $("#ip").prop("disabled", false);
            $(this).removeClass('btn-warning').addClass('btn-default');
        }

    });
});

Hope this helps.