I want to count and quantify the Array index on onclick control

Asked

Viewed 169 times

3

I want to create a simple element-based pagination within an array.

When arriving at the first and/or last element of the array, I would like to disable the respective navigation button (e.g., by changing from disabled=false for disabled=true)

Code

<button onclick="Anterior();" id="menos">Anterior</button> &nbsp; 
<span id='numero'>&nbsp;</span> &nbsp; 
<button onclick="Proximo();" id="mais">Próximo</button>

<script>
    var elemento = new Array(1, 2, 3, 2, 7);
    contar = 0

    Proximo = function() {
        contar ++;
              ...
    };

    Anterior = function() {
        contar --;
              ...        
    };

    // retorna o primeiro indice do array
    var menor = document.write(elemento.indexOf(searchElement[, fromIndex])) 
    // retorna o último índice do array
    var maior = document.write(elemento.slice(-1)[0])  

    if (contar == menor) {
        document.getElementById('menos').disabled=true;
    }
    if (contar == maior) {  
        document.getElementById('mais').disabled=true; 
    }
</script>

Then I would look aesthetically like this:

[ Previous ] - 3 - [ Next ]

I’d like him to count inside the element span

1 answer

4


You can do it like this:

var elemento = new Array(1, 2, 3, 2, 7);

var contar = 0;
var ele_len = elemento.length;
const spn = document.getElementById('numero');
const menos_btn = document.getElementById('menos');
const mais_btn = document.getElementById('mais');
menos_btn.disabled = true;
spn.innerHTML = contar+1;

Proximo = function(btn) {
menos_btn.disabled = false;
contar ++;
spn.innerHTML = contar+1;
if(contar >= ele_len - 1) {
	btn.disabled = true;
	contar = ele_len - 1;
}
};

Anterior = function(btn) {
mais_btn.disabled = false;
contar --;
spn.innerHTML = contar+1;
if(contar <= 0) {
	btn.disabled = true;
	contar = 0;
}
};
<button onclick="Anterior(this);" id="menos">Anterior</button> &nbsp; <span id='numero'></span> &nbsp; <button onclick="Proximo(this);" id="mais">Próximo</button>

Tip - To show the contents of a index of Array, just change the lines spn.innerHTML = contar+1; for this spn.innerHTML = elemento[contar];

  • Thanks Miguelito, funfou legal!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.