Split monetary value by checked box

Asked

Viewed 75 times

-1

I have doubts about how to make it work, check several "checkbox" or just one, enter a value in the "Total" input and show the split result, without refresh on the page, I tried with . on change, but I can’t get the checkded quantity and value and show the split value.

Example.

inserir a descrição da imagem aqui

$('input[type=checkbox]').on('change', function() {
  var total = $('input[type=checkbox]:checked').length;
  $('.resultado').html(total);
});


$('input').on('change', function() {
  $('.resultado2').html(this.value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="usuario[]" value="1">
<input type="checkbox" name="usuario[]" value="1">
<input type="checkbox" name="usuario[]" value="1">
<input type="checkbox" name="usuario[]" value="1">
<input type="text" value="0">
<div class="resultado2"></div>
<div class="resultado"></div>

  • You don’t need it to be monetary, just to share...

  • How does someone score negative and not even explain to me why? Ta wanting to harm me, bad faith!!!

1 answer

2


Following a simplification in the code:

function calcula() {
  var total = $('#total').val();
  var qtd = $('input[type=checkbox]:checked').length;
  $('#resultado').html( total / qtd );
}
$('input[type=checkbox]').on('change', calcula );
$('#total').on('input', calcula );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="usuario[]" value="1" checked>
<input type="checkbox" name="usuario[]" value="2" checked>
<input type="checkbox" name="usuario[]" value="3" checked>
<input type="checkbox" name="usuario[]" value="4" checked>
<input type="text" id="total" value="0">
<div id="resultado"></div>

  • Damn old man, of course, all "input". thank you!

  • Vlw man! Will help me a lot in the next

  • A question, perhaps silly, how to recover the value?

  • @Marcelloinfoweb depends on how you will use it. The value was calculated in this line: $('#resultado').html( total / qtd ); nothing prevents you from creating a variable by storing total / qtd. (or recover the value of the div using the same method we use to "write" to it)

Browser other questions tagged

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