Javascript activating form action

1

Situation: It has the form and one of the options I want is that it results in a sum of variables automatically by clicking a button or it can be without clicking, just the user just typing the values.

The problem is: he is already activating the action for the php page processing without the user completing the form. How could I do to show the result of the sum below the sum button (the same one that is activating the action)?

code not header:

<script type="text/javascript">  
    function calcula(){  
    var val1 = document.getElementById("pa").value;  
    var val2 = document.getElementById("di").value;
    var val3 = document.getElementById("insc").value;  
    var val4 = document.getElementById("outr").value;
    var soma = parseFloat(val1)+parseFloat(val2)+parseFloat(val3)+parseFloat(val4);  
    document.write("" + soma);  
}  
</script>

Now the code inside the html form that calls the function above:

<legend>Calcular total.</legend>    
<button id="calcular" onclick="calcula()">Calcular</button>

I accept suggestions for doing it in another way or another language.

    
asked by anonymous 24.02.2014 / 00:26

2 answers

1

By default, <button></button> submits the form when the button is pressed.

This behavior can be changed by indicating type="button" ( jsfiddle ).

<button id="calcular_btn" type="button" onclick="calcular()">X</button>

Alternatively, you can suppress the submission by returning the false value in the button event ( jsfiddle 1 , jsfiddle 2 ).

<button id="calcular_btn" onclick="calcular(); return false;">X</button>

There is also a third way to suppress the submission: via preventDefault ( jsfiddle DOM simple , jsfiddle jQuery ).

$('#calcular_btn').click(function (e) {
    calcular();
    e.preventDefault();
});
    
24.02.2014 / 00:57
0

If you all want to unsubscribe from the form, it is best to add the tag below to your page

24.02.2014 / 00:59