简体   繁体   中英

Dynamicaly refresh when new option is chosen

I'm trying to make JavaScript for Length conversion. The problem that i cant solve is this. When user load the page there is no problem, and JavaScript working. But when he choose another option, ie centimeters is still calculating meters .

Here is the address to test: http://martinpechacek.cz/convert/

<h2>Lenght</h2>
<p>
  <input id="input" type="number" placeholder="" oninput="LengthConverter(this.value)" onchange="LengthConverter(this.value)"> 

  From:
  <select id="from" name="from">
    <option id="from_meter" value="meter">meter</option>
    <option id="from_centimeter" value="centimeter">centimeter</option>
  </select> 

  To:
  <select id="to" name="to">
    <option id="to_kilometer" value="kilometer">kilometer</option>
  </select>
</p>
<p>Result: <span id="result"></span></p>
var idfrom = "meter";
var idto = "kilometer";

$("#from").change(function() {
  idfrom = $("#from").val();
});

$("#to").change(function() {
    idto = $("#to").val();
});

if (document.getElementById('from').value == "meter" && document.getElementById('to').value == "kilometer") {
  function LengthConverter(valNum) {
    document.getElementById("result").innerHTML = valNum / 1000;
  }
}

if (document.getElementById('from').value == "centimeter" && document.getElementById('to').value == "kilometer") {
  function LengthConverter(valNum) {
    document.getElementById("result").innerHTML = valNum / 100000;
  }
}

Your issue is that the logic that does the conversion is only executed when the page loads. To make it work when the values are changed you need to hook to those events and run the calculation there too.

You can also simplify the logic by retrieving all the needed values within the function which does the calculation. Finally, you should remove the outdated on* event attributes. Use unobtrusive event handlers instead. Try this:

 $("#from, #to").on('change', calculate); $('#input').on('input', calculate); calculate(); function calculate() { var divisor = $('#from').val() == 'meter' ? 1000 : 100000; $('#result').text($('#input').val() / divisor); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="col-md-8 offset-md-2 jumbotron"> <h2>Lenght</h2> <p> <input id="input" type="number" placeholder=""> From: <select id="from" name="from"> <option id="from_meter" value="meter">meter</option> <option id="from_centimeter" value="centimeter">centimeter</option> </select> To: <select id="to" name="to"> <option id="to_kilometer" value="kilometer">kilometer</option> </select> </p> <p>Result: <span id="result"></span></p> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM