Print form result outside the id using Javascript language?

Asked

Viewed 461 times

1

I have a small form that provides a result depending on the input of two values via form. I just want the result to be printed out of the result form. I’ve tried everything and I can’t. 3 possibilities occur:

  1. The result appears: [object][Object]: which occurred a few times when changing the schedule;

  2. Read the "Else" of the "third if" and there appears the phrase: Please redo your query. This occurs when I have the sentence: - var resultado = $("#valor3").val(); - (most common; it does not 'calculate' and understands that the value is null);

  3. 'Undefined' that occurs when I have this expression: var resultado = $("#resultado").val();

I leave the code for analysis, I am quite beginner in Javascript:

CODE ( .html file) - I leave in the form 'Undefined'

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Documento sem título</title>
<style type="text/css">
 .btn { }
 .n1 { }
 .n2 { }
 .n3 { }
</style>    
     <script type="text/javascript" src="jquery-1.8.3.js"></script>
   <script type="text/javascript" src="jquery.form.js"></script>
   <script type="text/javascript">
   function somarValores(){    
        var s1 = document.getElementById("s1").value;    
        var valor1 = convToFloat(s1) * 0.50;    
        var s2 = document.getElementById("s2").value;    
        var valor2 = convToFloat(s2) * 12;    
        var valor3 = valor1 + valor2;    
   document.getElementbyClassName(resultado).value = valor3;            
   }    

    function convToFloat(temp) {    
        var value;    

        if (temp.indexOf(',') == -1) {    
            temp = temp.replace(",", ".");    
        }    
        return parseFloat(temp); 
    }

    $(document).ready(function(){
       $(".btn").click(function(){

         var volume = $("#valor1").val();

     if(volume != 0){

      $("#n1").html("<font color='#828282' face='arial'><b>RELAT&Oacute;RIO</font><br><br>Volume do ambiente: <font color='blue'>" + volume + " m&sup3;</b></font>");

           }else{   

      $("#n1").html("<font color='#828282' face='arial'><b>RELAT&Oacute;RIO</font><br><br>Campo <i>Volume</i> n&atilde;o preenchido!</b>");

         }

         var pessoa = $("#valor2").val();

     if(pessoa != 0){

      $("#n2").html("<b>N&uacute;mero de pessoas: <font color='blue'>" + pessoa + "</b></font>");

           }else{   

      $("#n2").html("<b>Campo <i>N&uacute;mero de Pessoas</i> n&atilde;o preenchido!</b>");

         }

     var resultado = $("#resultado").val(); 

          if(resultado != 0){ 

           $("#n3").html("<b>N&uacute;mero de pessoas: <font color='blue'>" + resultado + "</b></font>");      

           }else{   

      $("#n3").html("<b>Por favor, refa&ccedil;a sua consulta!</b>");          

   }
       return false;

     })

    })


  </script>
</head>

<body>

 <br>

  <table width="30%" border="0">
    <tr>
     <td width="30%" align="center" valign="center" bgcolor="#EEEEE0">
      <font color="#8B8B83" face="arial"><b> - Estimativa de Carga T&eacute;rmica - </b></font>
        </td></tr></table><br>

 <table width="30%"><tr><td width="30%">
 <form method="post" action""><fieldset><legend></legend>
  <table width="100%" border="0">
    <tr>
     <td width="50%" align="right" valign="center">
      <b>Volume (&nbsp;m&sup3;): </b>
        </td>

     <td width="50%" align="center" valign="center">
       <input type="text" name="volume" id="valor1" size="5"/></td></tr>

      <tr>
       <td width="50%" align="right" valign="center">
         <b>N&#186; de Pessoas: </b>
        </td>

       <td width="50%" align="center" valign="center">
      <input type="text" name="pessoa" id="valor2" size="5"/></td></tr>


      <tr>
       <td width="50%" align="center" valign="center">
         <br><br>
        </td>

       <td width="50%" align="center" valign="center">
           <input type="text" name="resultado" id="valor3" hidden/>
           <input type="submit" value="Calcular Carga T&eacute;rmica" class="btn"/>
        </td></tr></table></fieldset>



 <br>
<dd><div id="n1"><p></p></div><br>
<div id="n2"><p></p></div><br>
<div id="n3"><p></p></div></dd>


</form>
</td></tr></table>
</body>
</html>
  • 2

    Hi, Fabiano, welcome to [en.so]. The formatting here on the site is with Markdown, has a quick guide here. The nice thing is to always try to reduce the code to the maximum until you leave only the part that demonstrates your problem. It’s a good technique because it helps you find the problem yourself, and there’s another guide to it: How to make a Minimal, Complete and Verifiable example

  • Your HTML and your script do not match well in the names. In javascript it references elements that do not find in HTML and has some errors such as document.getElementbyClassName(resultado) where this variable does not exist. Maybe there are no quotes there? Can you explain what you want to do? So we can use HTML and improve javascript.

  • And I don’t see where you’re calling the role either somarValores()

  • Hello Sergio, I tried with quotes and it didn’t work. Good what I want: Data input (2 or more inputs) and a printed output OUT of the form box. I can do it with the print of the result in the form, through readonly, but I want you to stay out. I believe it is not difficult, but I am beginner in javascript. That’s it!

  • And do you want to add the fields only? do you want to send the form to the server or just show on the screen?

  • Just show.

  • @Fabiano I’m out of time now but if no one answer soon help. Can you clarify the math you want to do? want to use the function somarValores or just "add up" the values?

  • Ok. The calculation (multiple sheets on different pages, but the idea is the same) is as follows::

  • Okay. The calculation (are several spreadsheets on different pages, but the idea is the same) is as follows: Value1 = input1 x N1; Value2 = input2 x N2; Result (to print) = Value1 + Value2; and N1 N2 are predefined numbers... As I said, input1 and input2 are inserted via form type text field and the result I want to print out. If I can help, it would be of great contribution to the assembly of my site. Ah, as to function, any one, as long as it solves my problem. Hug.

Show 4 more comments

1 answer

1

I think the Javascript you need is this:

function somarValores() {
    var s1 = document.getElementById("valor1").value;
    var valor1 = convToFloat(s1) * 0.50;
    var s2 = document.getElementById("valor2").value;
    var valor2 = convToFloat(s2) * 12;
    return [valor1, valor2];
}

function convToFloat(temp) {
    if (temp.indexOf(',') == -1) temp = temp.replace(",", ".");
    return parseFloat(temp);
}

$(document).ready(function () {
    $(".btn").click(function (e) {
        e.preventDefault(); // impedir a form de ser enviada para o servidor
        var input = somarValores(); // calcular os valores
        $('#n1 span').text(input[0]);
        $('#n2 span').text(input[1]);
        $('#n3 span').text(input[0] + input[1]);
    });
})

The HTML of the result I suggest so:

<div class="resultado">
     <h2>RELAT&Oacute;RIO</h2>
    <div id="n1">Volume do ambiente: <span></span> m&sup3;</div>
    <div id="n2">Número de pessoas: <span></span></div>
    <div id="n3">Total: <span></span></div>
</div>

There to format the layout/design should use CSS and not HTML.

For example:

.resultado {
    font-weight: 600;
}

.resultado span {
    color: blue;
}

The add value function fetches the input and returns the two calculated values in an array. So all you need to do is add.

Your HTML is unnecessarily complex. I think you could clean a lot there. I’m not sure why it has a <form> if you do not want to send the page to the server... I leave an example of the code working with your HTML changing the piece I put on top: http://jsfiddle.net/28nq8mcc/

  • 1

    Sergio, thanks by force... I stayed three days straight with this without solution. Thanks, it worked perfectly. Hug.

  • @Fabiano if the answer solved your problem can click and mark as accepted.

Browser other questions tagged

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