How to disable/enable an element with jQuery or Javascript

jQuery

Sometimes you need to disable/enable the form element like input or textarea. Jquery helps you to easily make this with setting disabled attribute to "disabled".
For e.g.:
//To disable 
$('.someElement').attr('disabled', 'disabled');


To enable disabled element you need to remove "disabled" attribute from this element or empty it's string. For e.g:
//To enable 
$('.someElement').removeAttr('disabled');
// OR you can set attr to "" 
$('.someElement').attr('disabled', '');


Javascript

My case was a bit different. I had to disable simple control element used without a form.
<a class="rotator" href="" onclick="return rotate(this, parameter, url)" >

I made a javascript like this:

/** script */
var disabled = false;
function rotate(button, parameter, url)
{
    if (disabled)
        return false;
    disabled = true;
    /** some before post operations like making element visually 
        disabled and adding some waiting animation to it */
    $.post(url, {
        parameter: parameter,
    }, function(data) {
        /** some after post operations for e.g. 
            changing alpha of elements back or disabling 
            waiting scroller  */
        disabled = false;
        return false;
    });
    return false;
}

So in general you have a boolean variable set to "false". Upon script first call it is set to "true" while script works up to it's completion. After completion boolean variable is set back again to "false". During script operations it will return "false", disallowing to run it again and making my <a> control disabled.


Comments/Suggestions? Please drop me a comment about your way if you have better maybe...

Comments

Popular posts from this blog

Django: Resetting Passwords (with internal tools)

Time Capsule for $25

Vagrant error: * Unknown configuration section 'hostmanager'.