1

Eu tenho esse código que funciona perfeitamente no Firefox, mas não consigo fazer ele funcionar no IE.

O usuário só poder escolher 10 unidades no total e quando chegar a 10 exibe um alert().

Alguém tem uma ideia ou uma solução melhor?

Aqui o JSfiddle

function getval() {
    var inputs, index,liste;
    inputs = document.getElementsByTagName('input');

    for(var key in inputs) {
        var value = inputs[key].value;
        var id = inputs[key].id;
        if (value > 0) liste =liste+id+"-"+value+";";
    }

    alert(liste.replace("undefined",""));
}


function mysum() {
    var inputs, index,liste;
    nbbroca=0;
    inputs = document.getElementsByTagName('input');
  
    for(var key in inputs) {
        var value = inputs[key].value;
        if (value > 0) nbbroca += parseInt(value);
      }

    if (nbbroca >= 10) alert(nbbroca);
}

$(":input").bind('change', function () {
    mysum();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<center>
    <form method="post" onsubmit="getval()">
        <table id="products" name="products" class="products">
            <tr class="figures">
                <th>
                    <a href="#">
                        <figure>
                            <img src="http://s33.postimg.org/j2so2jo1b/image1.png" alt="Product name" class="ProductTopCell img-rounded">
                              <p></p>
                        </figure>
                      </a>
                </th>
                <th>
                    <a href="#">
                        <figure>
                            <img src="http://s33.postimg.org/j2so2jo1b/image1.png" alt="Product name" class="ProductTopCell img-rounded">
                            <p></p>
                        </figure>
                    </a>
                </th>
                <th>
                    <a href="#">
                        <figure>
                            <img src="http://s33.postimg.org/j2so2jo1b/image1.png" alt="Product name" class="ProductTopCell img-rounded">
                            <p></p>
                        </figure>
                    </a>
                </th>
                <th>
                    <a href="#">
                        <figure>
                            <img src="http://s33.postimg.org/j2so2jo1b/image1.png" alt="Product name" class="ProductTopCell img-rounded">
                            <p></p>
                        </figure>
                    </a>
                </th>
                <th>
                    <a href="#">
                        <figure>
                            <img src="http://s33.postimg.org/j2so2jo1b/image1.png" alt="Product name" class="ProductTopCell img-rounded">
                            <p></p>
                        </figure>
                    </a>
                </th>
                <th>
                    <a href="#">
                        <figure>
                            <img src="http://s33.postimg.org/j2so2jo1b/image1.png" alt="Product name" class="ProductTopCell img-rounded">
                            <p></p>
                        </figure>
                    </a>
                </th>
            </tr>
            <tr class="quantity">
                <td>
                    <input  id="1011" name="1011" type="number" min="0" value="0" >
                </td>
                <td>
                    <input id="1012" name="1012" type="number" min="0" value="0" >
                </td>
                <td>
                    <input id="1013" name="1013" type="number" min="0" value="0" >
                </td>
                <td>
                    <input id="1014" name="1014" type="number" min="0" value="0" >
                </td>
                <td>
                    <input id="1015" name="1015" type="number" min="0" value="0" >
                </td>
                <td>
                    <input id="1016" name="1016" type="number" min="0" value="0" >
                </td>
            </tr>
        </table>
    
        <button type="submit">Post</button>
    </form>
</center>

3
  • Essa tag <meta> está a tornar o html inválido. Já experimentaste sem ela?
    – Sergio
    1/06/2016 às 11:50
  • Não vou testar, obg
    – SachaDee
    1/06/2016 às 12:29
  • Mesmo problema !
    – SachaDee
    1/06/2016 às 12:32

2 Respostas 2

3

O teu problema é que o getElementsByTagName retorna uma NodeList e o for .. in não deve ser usado para tal, ele deve ser usado para percorrer propriedades enumeráveis de objetos.

Se mudares os teus for...in para for var isso já vai funcionar (https://jsfiddle.net/892wxwsp/). Muda o teu código para:

function mysum() {
    var inputs, index, liste;
    nbbroca = 0;
    inputs = document.getElementsByTagName('input');

    for (var i = 0; i < inputs.length; i++) {

        var value = inputs[i].value;

        if (value > 0) nbbroca += parseInt(value);
    }
    if (nbbroca >= 10) alert(nbbroca);
}
1
  • Esta OK agora Obrigado.
    – SachaDee
    1/06/2016 às 16:53
1

Já que você está usando jQuery, poderia escrever as funções usando ele, dessa forma:

function sumAll() {
    var total = 0;

    $('.pra-somar').each(function() {
        var valor = parseInt(this.value);

        if (isNaN(valor)) {
            // poderia mostrar um alert('número inválido');
        } else {
            total += valor;
        }
    });

    return total;
}

function validate() {
    if(sumAll() > 10) {
        alert('A soma dos valores não pode ser maior que 10');
        // ainda pode logar os dados ou
        // guardar numa string e mostrar em um alert
        // $('.pra-somar').each(function() { console.log(this.value);});

        return false;
    }

    return true;
}

$(".pra-somar").bind('change', function () {
    validate();
});

Para cada <input> vocẽ precisaria adicionar a classe pra-somar e no <form> ficaria assim:

<form method="post" onsubmit="return validate()">

Espero ter ajudado \o/

Você pode ler a documentação do jQuery.each() no site oficial do jQuery

1
  • Vou testar, muito obrigado
    – SachaDee
    1/06/2016 às 16:54

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .