Summing up 3 inputs

Asked

Viewed 192 times

1

I have an input that is required with currency Mask but the user can enter 2 more inputs. I am not able to do this calculation, especially when the 3 inputs of values are not used.

Value input only appears if the user selects something in select.

Follow the codes:

<div class="col-sm-4">
<div class="row control-group">
    <div class="form-group col-xs-12 controls">
        <label>Cirurgia 1<span>*</span></label>
        <select class="form-control selectpicker" id="cirurgia" required data-validation-required-message="Escolha a cirurgia." multiple title="Selecione a Cirurgia">
            <optgroup data-max-options="1">
                <option>Abdominoplastia </option>
                <option>Blefaroplastia </option>
                <option>Dermolipectomia </option>
                <option>Implante Capilar </option>
                <option>Lipoaspiração </option>
                <option>Lipoescultura </option>
                <option>Lifting </option>
                <option>Mastopexia </option>
                <option>Mamoplastia de Aumento </option>
                <option>Mamoplastia Redutora </option>
                <option>Rinoplastia </option>
                <option>Rinoseptoplastia </option>
                <option>Outros </option>
            </optgroup>
        </select>
        <p class="help-block"></p>
    </div>
</div>
<div class="row control-group valorc1">
    <div class="form-group col-xs-12 controls">
        <label id="namec1"><span>*</span></label>
        <input type="text" class="form-control valor" id="valorc1" name="data[valorc1]" required data-validation-required-message="Digite o valor." autocomplete="off">
        <p class="help-block"></p>
    </div>
</div>

This code repeats more 2x obviously changing the ids to 2 and 3.

Below the result where the calculation should appear:

<div class="col-sm-4">
<div class="row control-group">
    <div class="form-group col-xs-12 controls">
        <label>Valor Total da Cirurgia<span>*</span></label>
        <input type="text" class="form-control valor" id="valor_total" name="data[valor_cirurgia]" readonly="readonly">
        <!-- <p id="valor_total">0,00</p> -->
    </div>
</div>

Now the jquery:

function calculaSoma(){
        var valor1 = $('input[name=data\\[valorc1\\]]');
        var valor2 = $('input[name=data\\[valorc2\\]]');
        var valor3 = $('input[name=data\\[valorc3\\]]');
        var tot = (valor + valor1 + valor2);
        var resultContainer = $('#valor_total');
        resultContainer.html(tot.formatMoney(2,',','.'));
        //alert(tot);
    }

If anyone can help me?

  • well that you could post the complete and executable code, including the libraries used, so that we can do some tests

4 answers

0

You are indexing the elements the respective variables "values", the correct form would be:

function calculaSoma(){
        var valor1 = $('input[name=data\\[valorc1\\]]').val();
        var valor2 = $('input[name=data\\[valorc2\\]]').val();
        var valor3 = $('input[name=data\\[valorc3\\]]').val();
        var tot = (valor1 + valor2 + valor3);
        var resultContainer = $('#valor_total');
        resultContainer.html(tot.formatMoney(2,',','.'));
        //alert(tot);
}

  • I did and it didn’t work out! But thanks for the help!

0

That’s what you wanted to do?

$(document).ready(function() {
  jQuery('#valorc1, #valorc2, #valorc3').keyup(function(){   
   var total = 0; 
   var total = parseFloat($('#valorc1').val(), 0);
   $('#valor_total').val(total);
   var valor2 = parseFloat($('#valorc2').val(), 0);
   if (valor2 == 0){
       $('#valor_total').val(total);
   }
   else {
       total += valor2;
       $('#valor_total').val(total);
   }
   var valor3 = parseFloat($('#valorc3').val(), 0);
   if (valor3 == 0){
       $('#valor_total').val(total);
   }
   else{
       total += valor3;
       $('#valor_total').val(total);
   }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<label>Cirurgia 1<span>*</span></label>
<select class="form-control selectpicker" id="cirurgia" required data-validation-required-message="Escolha a cirurgia." multiple title="Selecione a Cirurgia">
            <optgroup data-max-options="1">
                <option>Abdominoplastia </option>
                <option>Blefaroplastia </option>
                <option>Dermolipectomia </option>
                <option>Implante Capilar </option>
                <option>Lipoaspiração </option>
                <option>Lipoescultura </option>
                <option>Lifting </option>
                <option>Mastopexia </option>
                <option>Mamoplastia de Aumento </option>
                <option>Mamoplastia Redutora </option>
                <option>Rinoplastia </option>
                <option>Rinoseptoplastia </option>
                <option>Outros </option>
            </optgroup>
        </select>
        <p class="help-block"></p>

<input type="text" class="form-control valor" id="valorc1" name="data[valorc1]" required data-validation-required-message="Digite o valor." autocomplete="off">


<input type="text" class="form-control valor" id="valorc2" name="data[valorc1]" required data-validation-required-message="Digite o valor." autocomplete="off" value="0">

<input type="text" class="form-control valor" id="valorc3" name="data[valorc1]" value="0" required data-validation-required-message="Digite o valor." autocomplete="off">

<div class="col-sm-4">
<div class="row control-group">
    <div class="form-group col-xs-12 controls">
        <label>Valor Total da Cirurgia<span>*</span></label>
        <input type="text" class="form-control valor" id="valor_total" name="data[valor_cirurgia]" readonly="readonly">
        <!-- <p id="valor_total">0,00</p> -->
    </div>
</div>

  • That would be it but it is not mandatory to use the other inputs. If the guy puts only one value, in total it should appear, if use two, add the two.

  • @Eduardo just check in variable 2 and 3 if the respective ones are filled in if yes passes the value of the same, if does not pass 0, this before doing the sum of the variables

  • @Eduardo I edited the post, check if now meets what you need, now you are adding independent to fill only one, two or three fields.

  • Continue calculating only when I have 3 inputs.

  • Just to let you know that I’m a programming beginner, as you may have noticed.

0

Only converts to numbers.

var valor1 = parseFloat($('input[name=data\\[valorc1\\]]'));
var valor2 = parseFloat($('input[name=data\\[valorc2\\]]'));
var valor3 = parseFloat($('input[name=data\\[valorc3\\]]'));

You can use parseint() Also.

0

This script by clicking on an option from the select menu shows an input to insert a value, a clickable text Mais campos which makes it possible to add up to 2 more fields. If you want to add a larger number of fields just set the variable MaxInputs for a number of inputs allowed.

//script que mostra form quando um option for selecionado
    function showForm(that) {
        if (that.value != "") {
            document.getElementById("meuForm").style.display = "block";
        } else {
            document.getElementById("meuForm").style.display = "none";
        }
    }
    
	//script soma valor dos inputs e mostra resultado na tag span de id="Result"
	$(window).load(function(){

		var $form = $('#meuForm'),
		    $sumDisplay = $('#valor_total');  
	
		$form.on('keyup', '.valor', function ()
	
		{
		    var $summands = $form.find('.valor');
		    var sum = 0;
		    $summands.each(function ()
		    {
		        var value = Number($(this).val());
		        if (!isNaN(value)) sum += value;
		    });
		
		    $sumDisplay.val(sum);
		    
		    document.getElementById('Result').innerHTML = ": R$" +(sum)+",00"; 
		    
		});
	
	//script adiciona input
	$(document).ready(function() {
	var MaxInputs       = 2; //número máximo de inputs
	var InputsWrapper   = $("#InputsIncomeWrapper");
	var AddButton       = $("#AddMoreIncomeBox");
	var x = InputsWrapper.length; 
	var FieldCount=1;
		$(AddButton).click(function (e)
		{
		        if(x <= MaxInputs)
		        {
		            FieldCount++;
		            $(InputsWrapper).append('\
		            <div>\
		            <input type="text" class="form-control valor" id="valorc_'+ FieldCount +'"\
		            name="data[valorc1]" required data-validation-required-message="Digite o valor." autocomplete="off"\ />\
		            <a href="#" class="removeclass">Remover</a></div>');
		            x++;
		        }
		return false;
		});
		
	//script retira input e deduz valor correspondente do total
	$("body").on("click", ".removeclass", function (e) {
	        if (x > 1) {
	            $(this).parent('div').remove();
	            x--;
	        }
	        $('.valor').trigger('keyup');
	        return false;
	    })
	});
	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="col-sm-4">
<div class="row control-group">
<div class="form-group col-xs-12 controls">
    <label>Cirurgia 1<span>*</span></label>
    <select onchange="showForm(this);" class="form-control selectpicker" id="cirurgia" required data-validation-required-message="Escolha a cirurgia." multiple title="Selecione a Cirurgia">
        <optgroup data-max-options="1">
            <option>Abdominoplastia </option>
            <option>Blefaroplastia </option>
            <option>Dermolipectomia </option>
            <option>Implante Capilar </option>
            <option>Lipoaspiração </option>
            <option>Lipoescultura </option>
            <option>Lifting </option>
            <option>Mastopexia </option>
            <option>Mamoplastia de Aumento </option>
            <option>Mamoplastia Redutora </option>
            <option>Rinoplastia </option>
            <option>Rinoseptoplastia </option>
            <option>Outros </option>
        </optgroup>
    </select>
    <p class="help-block"></p>
</div>
</div>

<div id="meuForm" style="display: none;">
<input type="text" class="form-control valor" id="valorc" name="data[valorc1]" required data-validation-required-message="Digite o valor." autocomplete="off">
<div id="InputsIncomeWrapper"> </div>
<div class="col-sm-4">
	<div class="row control-group">
		<div class="form-group col-xs-12 controls">
			<input type="text" class="form-control valor2" id="valor_total" name="data[valor_cirurgia]" style="display: none;">
			<a href="#" id="AddMoreIncomeBox">Mais campos</a><br>
			<label>Valor Total da Cirurgia<span id="Result">*</span></label>
		</div>
	</div>
</div>
</div>

Browser other questions tagged

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