2016-04-06 64 views
0

我有下面的當前代碼,這是工作。問題是這個代碼將在一個窗體中,我不能嵌套窗體。我如何更改代碼,所以這與div父元素而不是form一起使用?計算器形式替代

<form> 
<script type="text/javascript"> 
    function inmet(form){ 
     form.in2met.value = ((form.inch.value -0) * 25.4).toFixed(2) 
    } 
</script> 
<div id="calcbody"> 
    <div class="calctitle">Convert <br />Inches to Millimetres</div> 
    <div class="singcalcquestion">Enter the Inches: 
     <input class="box1" type="text" name="inch" /> 
    </div> 
    <div class="singsubmit"> 
     <input onclick="inmet(this.form)" type="button" value="GO" />  
    </div> 
    <div class="singcalcanswer">Equals in Millimetres:<br /> 
     <input class="calcbox2" type="text" readonly="readonly" name="in2met" /> 
    </div> 
</div> 
</form> 

回答

2

一種選擇是使用Element.getElementsByClassName()或類似的方法來得到你想要的輸入字段:

<div id="form-root"> 
    <script type="text/javascript"> 
    function inmet(calcRoot){ 
    calcRoot.getElementsByClassName('calcbox2')[0].value = ((form.inch.value -0) * 25.4).toFixed(2); 
    } 
    // example: inmet(document.getElementById('form-root')) 
    </script> 
    <div id="calcbody"> 
    <div class="calctitle">Convert <br />Inches to Millimetres</div> 
    <div class="singcalcquestion">Enter the Inches: <input class="box1" type="text" name="inch" /></div> 
    <div class="singsubmit"><input onclick="inmet(document.getElementById('form-root'))" type="button" value="GO" /></div> 
    <div class="singcalcanswer">Equals in Millimetres:<br /><input class="calcbox2" type="text" readonly="readonly" name="in2met" /></div> 
    </div> 
</div> 
0

不是乾淨的解決方案,但它應該做的工作:

<div> 
 
    <script> 
 
     function inmet() { 
 
      document.getElementById('in2met').value = ((document.getElementById('inch').value - 0) * 25.4).toFixed(2) 
 
     } 
 
    </script> 
 
    <div id="calcbody"> 
 
     <div class="calctitle">Convert <br/>Inches to Millimetres</div> 
 
     <div class="singcalcquestion"> 
 
      <label for="inch">Enter the Inches:</label> 
 
      <input class="box1" type="text" name="inch" id="inch"/> 
 
     </div> 
 
     <div class="singsubmit"> 
 
      <input onclick="inmet()" type="button" value="GO"/> 
 
     </div> 
 
     <div class="singcalcanswer"> 
 
      <label for="in2met">Equals in Millimetres:</label> 
 
      <input class="calcbox2" type="text" readonly="readonly" name="in2met" id="in2met"/> 
 
     </div> 
 
    </div> 
 
</div>