Как сделать так, чтобы JavaScript работал последовательно - PullRequest
0 голосов
/ 01 мая 2018

У меня есть HTML-страница с простой формой, которая вычисляет произведение двух полей ввода и отображает результат в div. Он вызывает функцию JavaScript по щелчку. Однако после того, как я отправил первый раз, форма не работает со второго раза, страница продолжает обновляться.

<!DOCTYPE html>
<html>
    <head>
         <style>
				#header {
				    border: 1px solid lightgrey;
				    margin : -8px -8px 0;
				    background-color: lightgrey;
				 }
                 
                 #controls{
                     
                   margin-left: 475px;  
                   
                     
                 }
                 
                 #weight{
                     
                    margin-bottom:25px;
                 }
                 
                 #cost{
                     margin-bottom:25px;
                 }
                 
                 #compute{
                     
                     margin-bottom:25px;
                     margin-left: 300x
                 }
             
             #result{
                 
                   margin-left: 50px
             }
		</style>
</head>
    
<body>
    <div id="header">
        <table style="width:100%">
            <tr style="width:100%">
                <td style="width:20%">
                    <span>
                        <img align="left" src="logo.jpeg" width="120px" height="120px">
                    </span>
                </td>    
                <td style="width: 60%;">
                    <span>
                        <center>
                            <h1>DATAX Shipping Company</h1>
                        </center>
                    </span>
                </td>
                <td style="width: 40%; padding-bottom: 7%;padding-left:5%;">
                    <span>
                        <a href="#" id="signup">Sign up</a>
                        <a href="#" id="login" style="padding-left:30px">Log in</a>
                    </span>
                </td>
            </tr>
        </table>
    </div>
    <form id="controls">
    	 <div class="title">
          <h3>Calculation of Shipping charge</h3>   
    	 </div>
            
       <div><label> Total Product Weight <input id="weight"/></label></div>
       <div><label>Shipping cost (Per Kg) <input id="cost"/></label></div>
         <button id="compute" onclick="return result()"/>Compute</button>
        <div id="result"></div>
</form>
       

<script type="text/javascript">
    
    var weight;
    var cost;
    var result;
    function result(){
        
        weight=document.getElementById("weight").value;
        cost=document.getElementById("cost").value;
        console.log(weight);
        console.log(cost);
        result=weight*cost;
        console.log(result);
        document.getElementById("result").innerHTML="The Total Shipment charge is "+result;
        return false;
    }


</script>
</body>
</html>

Я тестирую по сценариям ниже

вес = 4, расстояние = 5 Вес = 10, расстояние = 15

Со второй итерации и далее кажется, что она не работает

Ответы [ 3 ]

0 голосов
/ 01 мая 2018

Это потому, что вы используете то же имя (результат) в качестве переменной и снова в качестве имени функции в той же области видимости. Вы должны изменить их. Вы можете изменить имя функции на (getResult).

0 голосов
/ 01 мая 2018

Я бы сделал это так:

document.getElementById("compute").addEventListener('click', result);
function result(e) {
    // Since its a form, you need to use preventDefault()
    e.preventDefault();
    // Define input variables
    var weight = document.getElementById("weight").value;
    var cost   = document.getElementById("cost").value;
    // Result variable
    var result = document.getElementById("result");
    // Check if the value is a number
    if( isNaN(weight) || isNaN(cost) ) {
        result.innerHTML = "Please enter a Valid Number!";
    }
    // Final result
    else {
        result.innerHTML = "The Total Shipment charge is " + (weight * cost);
    }
}

document.getElementById("resetForm").addEventListener('click', resultReset);
function resultReset(e) {
    // prevent submit
    e.preventDefault();
    // Reset form
    document.getElementById("controls").reset();
}
#header {
	border: 1px solid lightgrey;
	margin : -8px -8px 0;
	background-color: lightgrey;
}

#controls{
	margin-left: 475px;
}

#weight{
	margin-bottom:25px;
}

#cost{
	margin-bottom:25px;
}

#compute{
	margin-bottom:25px;
	margin-left: 300x
}

#result{
	margin-left: 50px
}
<div id="header">
  <table style="width:100%">
    <tr style="width:100%">
      <td style="width:20%">
        <span>
          <img align="left" src="logo.jpeg" width="120px" height="120px">
        </span>
      </td>    
      <td style="width: 60%;">
        <span>
          <center>
            <h1>DATAX Shipping Company</h1>
          </center>
        </span>
      </td>
      <td style="width: 40%; padding-bottom: 7%;padding-left:5%;">
        <span>
          <a href="#" id="signup">Sign up</a>
          <a href="#" id="login" style="padding-left:30px">Log in</a>
        </span>
      </td>
    </tr>
  </table>
</div>

<form id="controls">
    <div class="title">
        <h3>Calculation of Shipping charge</h3>   
    </div>
    <div><label> Total Product Weight <input id="weight"/></label></div>
    <div><label>Shipping cost (Per Kg) <input id="cost"/></label></div>
    <button id="compute">Compute</button>
    <button id="resetForm">Reset</button>
    <div id="result"></div>
</form>
0 голосов
/ 01 мая 2018

Вы перезаписываете переменную result внутри функции, вам нужно заменить ее на что-то другое:

 var weight;
        var cost;
        var result;
        function result(){
            
            weight=document.getElementById("weight").value;
            cost=document.getElementById("cost").value;
            console.log(weight);
            console.log(cost);
            xresult=weight*cost;
            console.log(xresult);
            document.getElementById("result").innerHTML="The Total Shipment charge is "+xresult;
            return false;
        }
#header {
				    border: 1px solid lightgrey;
				    margin : -8px -8px 0;
				    background-color: lightgrey;
				 }
                 
                 #controls{
                     
                   margin-left: 475px;  
                   
                     
                 }
                 
                 #weight{
                     
                    margin-bottom:25px;
                 }
                 
                 #cost{
                     margin-bottom:25px;
                 }
                 
                 #compute{
                     
                     margin-bottom:25px;
                     margin-left: 300x
                 }
             
             #result{
                 
                   margin-left: 50px
             }
<div id="header">
        <table style="width:100%">
            <tr style="width:100%">
                <td style="width:20%">
                    <span>
                        <img align="left" src="logo.jpeg" width="120px" height="120px">
                    </span>
                </td>    
                <td style="width: 60%;">
                    <span>
                        <center>
                            <h1>DATAX Shipping Company</h1>
                        </center>
                    </span>
                </td>
                <td style="width: 40%; padding-bottom: 7%;padding-left:5%;">
                    <span>
                        <a href="#" id="signup">Sign up</a>
                        <a href="#" id="login" style="padding-left:30px">Log in</a>
                    </span>
                </td>
            </tr>
        </table>
    </div>
    <form id="controls">
    	 <div class="title">
          <h3>Calculation of Shipping charge</h3>   
    	 </div>
            
       <div><label> Total Product Weight <input id="weight"/></label></div>
       <div><label>Shipping cost (Per Kg) <input id="cost"/></label></div>
         <button id="compute" onclick="return result()"/>Compute</button>
        <div id="result"></div>
</form>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...