Sum and Subtract values with checkbox and select

Asked

Viewed 217 times

0

Could someone give me a hand? I need to do a checkbox sum and subtraction and select with values and show the result as the fields are selected, someone could give me a path to follow?

  • You can’t understand what you want. Can you try to be clearer and give an example of what you intend to do? You can [Dit] your question at any time.

  • First, read these posts 1 - https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%C3%83o-fazer/ 2 - https://answall.com/help/mcve

  • Ask at least the HTML with the checkbox and select

  • The code is missing for us to analyze.

1 answer

0


Here’s a simple example, since you haven’t made it very clear what you need.

<select id="opcao_soma_val1" name="soma">
  <option value="1" selected>1</option>
  <option value="2">2</option>
  <option value="3">3</option>
<select>

<input  id="opcao_soma_val2" value="1" type="number" step="1" min="1" max="10">
<div id="resultado"><!-- aqui vem o resultado --></div>
<button id="somar">Somar</button>
<button id="subtrair">Subtrair</button>

<script
  src="http://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous">
</script>
<script>

$(function(){
  $(document).on('click','#somar', function(){
     somar();
  });
 $(document).on('click','#subtrair', function(){
     subtrair();
  });

});
function subtrair(){
     var val1 = $('#opcao_soma_val1').val();
     var val2 = $('#opcao_soma_val2').val();
     var result = (parseInt(val1) - parseInt(val2));
     $('#resultado').text(result);
  } 
function somar(){
     var val1 = $('#opcao_soma_val1').val();
     var val2 = $('#opcao_soma_val2').val();
     var result = (parseInt(val1) + parseInt(val2));
     $('#resultado').text(result);
  } 
</script>

To add in real time, just make Blur in the last field.

Example:

$('#opcao_soma_val2').on('blur', function(){
  somar();
});

Fiddle of the example

  • Would that be right, is there the possibility of the result being displayed without clicking the button? The result be presented in "real time", thanks for the help!

  • Yes of course, look here: https://jsfiddle.net/ivanferrer/nq9Lts0f/

Browser other questions tagged

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