[javascript] document.getElementById('btnid').disabled is not working in firefox and chrome

I'm using JavaScript for disabling a button. Works fine in IE but not in FireFox and chrome, here is the script what I'm working on:

function disbtn(e) { 
    if ( someCondition == true ) {
       document.getElementById('btn1').disabled = true;
    } else {
       document.getElementById('btn1').disabled = false;
    }

And in my html I have:

<input type="button" id="btn1" value="submit" />

This question is related to javascript getelementbyid

The answer is


use setAttribute() and removeAttribute()

function disbtn(e) { 
    if ( someCondition == true ) {
       document.getElementById('btn1').setAttribute("disabled","disabled");
    } else {
       document.getElementById('btn1').removeAttribute("disabled");
    }
}

SEE DEMO


Another alternative :

document.formname.elementname.disabled=true

Work on FF and IE ! :)


There are always weird issues with browser support of getElementById, try using the following instead:

// document.getElementsBySelector are part of the prototype.js library available at http://api.prototypejs.org/dom/Element/prototype/getElementsBySelector/

function disbtn(e) { 
    if ( someCondition == true ) {
        document.getElementsBySelector("#btn1")[0].setAttribute("disabled", "disabled");
    } else {
        document.getElementsBySelector("#btn1")[0].removeAttribute("disabled");
    }    
}

Alternatively, embrace jQuery where you could simply do this:

function disbtn(e) { 
    if ( someCondition == true ) {
        $("#btn1").attr("disabled", "disabled");
    } else {
        $("#btn1").removeAttr("disabled");
    }    
}

Some time some javascript functions does not work on some specific browser. I would suggest you to start using JQuery, which gives you normalized JS, taking care of different browser requirement

$('#btn1').each(function(){
    this.disabled = false;
});

I've tried all the possibilities. Nothing worked for me except the following. var element = document.querySelectorAll("input[id=btn1]"); element[0].setAttribute("disabled",true);


stay true to native (Boolean) property support and its powerful syntax like:

[elem].disabled = condition ? true : false; //done!

and for our own good collective coding experience, -please insist on others to support it as well.


Try setting the disabled attribute directly:

if ( someCondition == true ) {
   document.getElementById('btn1').setAttribute('disabled', 'disabled');
} else {
   document.getElementById('btn1').removeAttribute('disabled');
}