1

How would I do an if...then statement for this piece of code?

  $('body').on('click', '.icon-lock', function () {
        var lockedarea = $(this).parents(0).eq(2);
    $(lockedarea).find('input[type=text],input[type=checkbox],textarea,select').prop('disabled', true);
  });

Right now when I click it, what I want to happen happens as far as those inputs becoming uneditable. However I'm trying to say that if this button is pressed, then this happens. And if it's pressed again, then .prop('disabled', false). However as I'm just starting out, I get confused easily when doing this sort of thing.

bmoneruxui
  • 303
  • 7
  • 17

3 Answers3

5

You need to keep track of whether you want to disable it or not in some sort of variable. Try this:

var disable = true;
$('body').on('click', '.icon-lock', function () {
    var lockedarea = $(this).parents(0).eq(2);
    $(lockedarea).find('input[type=text],input[type=checkbox],textarea,select').prop('disabled', disable);
    disable = !disable;
});
Colin DeClue
  • 2,194
  • 3
  • 26
  • 47
3

Use some flag:

var isDisabled = false;
$('body').on('click', '.icon-lock', function () {
    var lockedarea$ = $(this).parents(0).eq(2),
        inputs$ = lockedarea$.find('input[type=text],input[type=checkbox],textarea,select');
    if ( isDisabled ) {
        isDisabled = false;
        inputs$.prop('disabled', false);
    } else {
        isDisabled = true;
        inputs$..prop('disabled', true);
    }
});
u_mulder
  • 54,101
  • 5
  • 48
  • 64
2

Just replace your current .prop with this:

.prop('disabled', function (_, val) { return ! val; });
hiattp
  • 2,326
  • 1
  • 20
  • 23