1

Tenho um textbox, e dois botões mais e menos, quero decrementar até zero, consegui fazer porem não consigo diminuir de 1:

HTML

<asp:TextBox ID="txtAcrescimo" type="number" CssClass="form-control" MaxLength="18"
     runat="server" onblur="javascript:defineQuantidade();"></asp:TextBox>

  <div style="display: inline-block; margin-right:10px;">
    <input id="aumentaAcrescimo" type="button" onclick="aumentaAcrescimo()" style="width: 35px; margin-left:10px; height: 35px" value="+"  />
    <td>
      <input id="diminuiAcrescimo" type="button" style="width: 35px; height:35px " value="-" />
  </div>    

JS

$("#txtAcrescimo").val(1);

//aumenta acrescimo
$("#aumentaAcrescimo").click(function () {
  var acrescimo = parseInt($("#txtAcrescimo").val());

  if (acrescimo <= 0) {
    $("#txtAcrescimo").val(1);
  } else {
    acrescimo++;
  }

  $("#txtAcrescimo").val(acrescimo);

});

$("#diminuiAcrescimo").click(function () {
  var acrescimo = parseInt($("#txtAcrescimo").val());

  if (acrescimo <= 0) {
    $("#txtAcrescimo").val(1);
  } else if(acrescimo > 1) {
    acrescimo--;
  }

  $("#txtAcrescimo").val(acrescimo);
});

Consegui dessa forma e funcionou, porem começa em 1, tentei aplicar a lógica para começar de zero e não vai.

2
  • essa forma que mostrei, é aplicada para começar de 1, e diminuir até 1, como ficaria a correção para começar de 0, e diminuir até zero?
    – War Lock
    10/04/2015 às 12:15
  • Se substituir onde tem 0 por -1 e 1 por 0 não resolve não? 10/04/2015 às 12:18

2 Respostas 2

6

Podes simplificar assim:

$("#txtAcrescimo").val(0); // valor de inicio

$("#aumentaAcrescimo").click(function () {
    var input = $("#txtAcrescimo")[0];
    input.value = parseInt(input.value, 10) + 1;
});

$("#diminuiAcrescimo").click(function () {
    var input = $("#txtAcrescimo")[0];
    var decrescimo = parseInt(input.value, 10) - 1;
    input.value = decrescimo < 1 ? 0 : decrescimo ;
});

jsFiddle: https://jsfiddle.net/q14pfp0h/2/

2
  • Funcionou, se eu quizesse fazer a mesma coisa limitando a 1, o que eu precisaria mudar?
    – War Lock
    10/04/2015 às 12:28
  • 1
    consegui aqui, vlw
    – War Lock
    10/04/2015 às 12:29
3

Já tens uma excelente solução, vou deixar uma versão fazendo uso das potencialidades de Jquery para efeitos de redução de código e otimização do mesmo:

var $input = $("#txtAcrescimo");

$input.val(0);

$(".altera").click(function(){
    if ($(this).hasClass('acrescimo'))
        $input.val(parseInt($input.val())+1);
    else if ($input.val()>=1)
        $input.val(parseInt($input.val())-1);
});

Exemplo

Também no JSFiddle.

// Cache do elemento para evitar constantes ciclos de procura pelo mesmo
var $input = $("#txtAcrescimo");

// Colocar a 0 ao início
$input.val(0);

// Aumenta ou diminui o valor sendo 0 o mais baixo possível
$(".altera").click(function() {
  if ($(this).hasClass('acrescimo'))
    $input.val(parseInt($input.val()) + 1);
  else if ($input.val() >= 1)
    $input.val(parseInt($input.val()) - 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<input type="text" id="txtAcrescimo" />
<button type="button" class="altera acrescimo">+</button>
<button type="button" class="altera decrescimo">-</button>


Nota:
Como podemos ver na documentação, o elemento <button/> quando do tipo button: type="button", não tem uma ação padrão, tornando-se desnecessário utilizar o método preventDefault.

0

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 .