2017-09-26 4 views
0

私は、いくつかのドロップダウンメニューに異なるオプションを持つフォーム用のコードを持っており、同じ惑星を選択できないように警告メッセージを作成します今。私は1つの入力を入れることができるので、入力用に1つのテキストボックスに1つの入力を無効にしています。ドロップダウンで惑星の重さを計算し、それを入力タイプに出力する

私の質問は、選択したドロップダウンボックスに基づいて惑星の重量を計算する方法です。また、インプットタイプで印刷/表示します。アースを選択し、入力タイプ(ウェイト)が60Nの場合、私の2番目の選択肢は金星です。それは私の重量を計算し、入力タイプに印刷/表示します。

以下はおおよそ自分のHTMLコードとJavaScriptコードです。私はJavaScriptが初めてです。

HTML:

<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
</head> 
    <body> 
    <select name="select1" id="select1" onchange="process_selection(this)"> 
<option value="">-- choose one --</option> 
    <option value="0">Earth</option> 
    <option value="1">Venus</option> 
    <option value="2">Mars</option> 
    <option value="3">Jupiter</option> 
    <input type="text" name="123" id="text1" 
    onchange="process_selection(this)" placeholder=""> N 
</select> 
    <br> 

    <select name="select2" id="select2" onchange="process_selection(this)"> 
<option value="">-- choose one --</option> 
    <option value="0">Earth</option> 
    <option value="1">Venus</option> 
    <option value="2">Mars</option> 
    <option value="3">Jupiter</option> 

    <input type="text" name = "123" id="text2" 
    onchange="process_selection(this)" placeholder=""> N 


    </select> 

のjavascript:

<script type="text/javascript"> 

function process_selection(obj) 
{ 


var input1 = document.getElementById("select1").value; 
var input2 = document.getElementById("select2").value; 
var texta = document.getElementById("text1"); 
var textb = document.getElementById("text2"); 


if(input1 == input2) 
{ 
    alert("Please select other planet"); 
} 
if(texta.value != "") 
    { 
    document.getElementById("text2").disabled = true ; 

    } 
if(textb.value != "") 
{ 
    document.getElementById("text1").disabled = true ; 

} 

    // var xx = input1.options[input1.selectedIndex].value; 
    var SurfaceGravityEarth = 1; 
    var SurfaceGravityVenus= 0.907; 
    var SurfaceGravityMars= 0.377; 
    var SurfaceGravityJupiter= 2.364; 
    var weight1 , weight2; 
    // var sg1; 
    // var sg2; 

    if (input1 == "0" ) 
{ 

weight1 = document.getElementById("text1") * SurfaceGravityEarth; 
} 

    if (input2 == "1" ) 
    { 
    weight2 = document.getElementById("text1") * SurfaceGravityVenus ; 
    document.getElementById("text2").value= weight2 ; 
    } 

} 

私は演算部でこだわっています。

+0

両方のための番号()メソッドを使用することができます要素タイプ。この場合、乗算はできません。おそらく 'document.getElement( 'xxxx')。value'を使用してその要素の値を取得し、この文字列値を数値型に変換して変換する必要がありますそれを使って数学の仕事をする – Noah

答えて

1

まず、textboxの値を取得し、数値型(整数、浮動小数点数など)に変換します。型を整数に変換する

weight1 = parseInt(document.getElementById("text1").value) * SurfaceGravityEarth; 

使用のparseInt(): 次のコードを試してください。 あなたがタイプの使用parseFloatはを(floatに変換したい場合) か、単に `DOMであるあなたは、` document.getElement(「XXXX」)から得るもの、整数および浮動小数点数