2017-09-15 8 views
-1

2つの入力フィールドの値をonclickイベントで追加できません。 私はすべての種類のエラーを受け取りました。私が得る最後のエラーは、「例外TypeError:のdocument.getElementById関数 ラインではありません:8」である2つの入力フィールドの値を追加できません

これは、コード

<!DOCTYPE html> 
<html> 
    <head> 
     <meta charset="UTF-8"> 
     <title>calculadora</title> 
    <script> 
     function eventsumar(num1, num2) { 
     var x = document.getelementById("num1"); 
     var y = document.getelementById("num2"); 
     var z = x + y; 
     }; 
    </script> 
    </head> 
    <body> 
     <form> 
      <input type="number" id="num1"> 
      <strong>+</strong> 
      <input type="number" id="num2"> 
      <button type="button" onclick=eventsumar(num1, num2) value="Sumar">sumar</button> 
      <strong>=</strong> 
     </form> 
     <p id="resu"></p> 
    </body> 
</html> 
+1

ケースは、それがgetElementByIdをなぜあなたは、あなたも使用していないパラメータを渡すために(しよう)している –

+0

をgetElementByIdをいない、JavaScriptで重要? – j08691

答えて

0

コード内の3つの問題があります。

  • document.getElementByIdは大文字と小文字が区別されます。 document.getelementByIdは機能しません。
  • document.getElementByIdはそのIDに参照オブジェクトを返します。値を読み取るには.valueを追加する必要があります。
  • 関数内で変数を渡す必要はありません。関数自体から変数を読み込んでいます。

 function eventsumar() { 
 
     var x = document.getElementById("num1").value; 
 
     var y = document.getElementById("num2").value; 
 
     var z = parseInt(x) + parseInt(y); 
 
     document.getElementById("resu").innerText = z; 
 
     
 
     };
<!DOCTYPE html> 
 
<html> 
 
    <head> 
 
     <meta charset="UTF-8"> 
 
     <title>calculadora</title> 
 
    
 
    </head> 
 
    <body> 
 
     <form> 
 
      <input type="number" id="num1"> 
 
      <strong>+</strong> 
 
      <input type="number" id="num2"> 
 
      <button type="button" onclick="eventsumar()" value="Sumar">sumar</button> 
 
      <strong>=</strong> 
 
<p id="resu"></p> 
 
     </form> 
 
     
 
    </body> 
 
</html>

+0

それはどちらもうまくいきません... – Yourdaman

+0

@Yourdaman 'Run Code Snippet'をクリックして値を入力し、submitをクリックしてください。 –

+0

偉大な、私はそれを考え出した – Yourdaman

関連する問題