Check if button is disabled - JavaScript

3

I have this button, and I need to check with JavaScript if it is disabled, but I do not know how to do that. Here's the HTML:

<button type="button" title="Finalizar Compra" class="btn btn-proceed-checkout btn-checkout no-checkout" disabled="disabled">
    <span>Finalizar Compra</span>
</button>

Do you see disabled="disabled" ? So how do I verify this?

What I already did was:

var b = document.getElementsByClassName("btn btn-proceed-checkout btn-checkout no-checkout");

if(b == ???) { //Aqui que não sei o que fazer ???
    alert("Pedido minimo de: R$: 1250,00");
}
    
asked by anonymous 11.07.2017 / 16:05

2 answers

5

Note that the method getElementsByClassName returns a collection, so to get the button only, you can get the first item in the collection or use an alternative like getElementById , already with the element, to check if it is disabled or not, just check the disabled attribute:

var b = document.getElementsByClassName("btn btn-proceed-checkout btn-checkout no-checkout")[0];

if (b.disabled) { //Aqui que não sei o que fazer ???
  alert("Pedido minimo de: R$: 1250,00");
}
<button type="button" title="Finalizar Compra" class="btn btn-proceed-checkout btn-checkout no-checkout" disabled="disabled">
<span><span>Finalizar Compra</span></span>
</button>
    
11.07.2017 / 16:11
3

If you need to find a specific element (either by tag, class, id, data attributes, etc.), use document.querySelector() . It makes more sense than to make use of this getElementsByClassName .

var button = document.querySelector('.btn.btn-proceed-checkout');

if(button.disabled)
  console.log('Está desabilitado.');
<button type="button" title="Finalizar Compra" class="btn btn-proceed-checkout btn-checkout no-checkout" disabled="disabled">
    <span>Finalizar Compra</span>
</button>

I could get it in other ways too, for example:

// Pelo título.
var button = document.querySelector('button[title="Finalizar Compra"]');

// Pelo atributo 'disabled'.
var button = document.querySelector('button[disabled]');

// Tendo atributo disabled e título específico.
var button = document.querySelector('button[disabled][title="Finalizar Compra"');

// Tendo todas as classes do seu botão.
var button = document.querySelector('.btn.btn-proceed-checkout.btn-checkout.no-checkout');

If you need to get a collection of elements, use document.querySelectorAll() .

    
11.07.2017 / 17:51