Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lock/unlock HTML element with Jquery on certain condition?

Tags:

jquery

I can better explain it with Raw script.

<script>
    $(document).ready(function () {
        $("Div").  //lock div here

        var condition=$("#value").val();
        if(condition==true){unlock div here}
        else{do nothing}
    });
</script>

Is there any jquery widget i have to include?

By saying lock/unlock I mean Enable/Disable.

like image 473
RollerCosta Avatar asked Jan 31 '12 07:01

RollerCosta


2 Answers

Don't do $("#Div").attr('disabled','true');, the main problem here is that with 1.6 (or sth around that) the comparison with == true is broken, if the attributes value is disabled (see http://jsfiddle.net/2vene/1/ (and switch the jquery-version)). You should rather go for is().

Secondly div doesn't support disabled, use some input. In this case your code will look like

<script>
  $(document).ready(function () {
    $("#controlId").attr('disabled','disabled');  //lock input control here

    var condition = $("#value").val();
    if(condition == true)
          $("#controlId").removeAttr('disabled');//{unlock input control here}
    else{do nothing}
});
</script>

You can check jQuery FAQ.

EDIT

Optionally you can use readonly on div to lock / unlock mechanism. Check demo of readonly.

like image 114
Amar Palsapure Avatar answered Oct 21 '22 17:10

Amar Palsapure


<script>
    $(document).ready(function () {
        $("Div").attr('disabled','true');  //lock div here


        var condition=$("#value").val();
        if(condition==true)
              $("Div").attr('disabled','false');//{unlock div here}
        else{do nothing}
    });
</script>
like image 43
TwTw Avatar answered Oct 21 '22 17:10

TwTw