I wrote a script and a form, according to which calculations are made and counted by clicking on the "Calculate" button. Please help me how to implement demo calculations: when you click on the "Demo" button, the default values ​​are inserted into their respective fields, but before clicking on the "Demo" button, the fields must be empty.

function proverka(input) { var value = input.value; var rep = /[-;":'a-zA-Zа-яА-Я\\=`ё/\*++!@#$%\^&_№?><]/; if (rep.test(value)) { value = value.replace(rep, ''); input.value = value; } } function areaRectangle() { this.calc1(); var H1 = +document.forma1.t1.value || 0; var H2 = +document.forma1.t2.value || 0; var l1 = H2 - H1; document.forma1.t3[0].value = H1; document.forma1.t3[1].value = H2; document.forma1.t3[2].value = l1; if ((H1 == 0) || (H2 == 0) || (p1 == 0) || (p2 == 0)) { //сообщаем пользователю в диалоговом окне, о том что при нажатии на кнопку вычислить, alert('Входные данные не могут быть равны 0'); //входные данные "ограничены", поэтому если пользователь return; //введет их неправильно, то ему придётся ввести данные ещё раз, но на этот раз правильно } if ((H1 < 0) || (H2 < 0) || (p1 < 0) || (p2 < 0)) { alert('Входные данные не могут быть меньше 0'); return; } if (H2 < H1) { alert('H2 должно быть больше H1'); return; } var p1 = document.forma1.t4.value; var p2 = document.forma1.t5.value; var L = H2 - l1 * (p1 / p2 || 0); document.forma1.res.value = L; } function calc1() { //в подрасчёте есть промежуточное значение l1 console.log(1); //пользователь узнает чему равно l1, только после ввода H1 и H2, и нажатия на var H1 = +document.forma1.t1.value || 0; //текстовое поле t3 var H2 = +document.forma1.t2.value || 0; var l1 = H2 - H1; document.forma1.t3[0].value = H1; document.forma1.t3[1].value = H2; document.forma1.t3[2].value = l1; } document.addEventListener("DOMContentLoaded", function(event) { document.forma1.t1.addEventListener("keyup", calc1); document.forma1.t2.addEventListener("keyup", calc1); }); 
 <form name="forma1" style="background-color:#44944A;"> <!-- поменяю цвет формы --> <div id="resizable"> <!--"подрасчёт 1.1"--> <table align="center"> <br> <p align="center">Глубина установки конца заливочных труб</p> <tr> <td height="40px"> <div class="price" title="H1">Расстояние от устья скважины до нижних отверстий фильтра, м;</div> <input name="t1" type="text" align="right" size="4" maxlength="8" onkeyup="return proverka(this)" id="t3"> </td> </tr> <tr> <td height="40px"> <div class="price" title="H2">Расстояние от устья скважины до верхних отверстий фильтра, м;</div> <input name="t2" type="text" align="right" size="4" maxlength="8" onkeyup="return proverka(this)" id="t3"> </td> </tr> <tr> <td height="40px"> <div class="price">Интервал отверстий фильтра, м;</div> <input name="t3" type="text" align="right" size="4" maxlength="8" onkeyup="return proverka(this)" id="t3"> </td> </tr> <tr> <td height="40px"> <div class="price">Плотность цементного раствора, кг/м<sup>3</sup>;</div> <input name="t4" type="text" align="right" size="4" maxlength="8" onkeyup="return proverka(this)"> </td> </tr> <tr> <td height="40px"> <div class="price">Плотность жидкости, находящейся в скважине, кг/м<sup>3</sup>;</div> <input name="t5" type="text" align="right" size="4" maxlength="8" onkeyup="return proverka(this)"> </td> </tr> <tr> <td> <input type="button" name="button" value="Вычислить" onClick="areaRectangle();"> <input type="text" name="res" size="10"> </td> </tr> </table> </div> <br> </form> 

The calc1 function is needed to calculate the intermediate value of l1

Under the formula, there are default values ​​for demo calculations. enter image description here

  • Alternatively, input, add the data attribute with values ​​for demo accounts. When you click on the demo button, you write these values ​​into inputs and start the calculation function. - Dmitriy Kondratiuk
  • There is a simpler option, but I don’t think what happens with two id: once id are set to calculate the intermediate value, and the second time is needed for demo - Rem
  • "When you click on the demo button, you write these values ​​in the input" and how to do it? - Ram
  • Added answer. In javascript is not very strong, therefore implemented an addition using jquery. - Dmitriy Kondratiuk

1 answer 1

If through jqery, something like this:

  function proverka(input) { var value = input.value; var rep = /[-;":'a-zA-Zа-яА-Я\\=`ё/\*++!@#$%\^&_№?><]/; if (rep.test(value)) { value = value.replace(rep, ''); input.value = value; } } function areaRectangle() { this.calc1(); var H1 = +document.forma1.t1.value || 0; var H2 = +document.forma1.t2.value || 0; var l1 = H2 - H1; document.forma1.t3[0].value = H1; document.forma1.t3[1].value = H2; document.forma1.t3[2].value = l1; if ((H1 == 0) || (H2 == 0) || (p1 == 0) || (p2 == 0)) { //сообщаем пользователю в диалоговом окне, о том что при нажатии на кнопку вычислить, alert('Входные данные не могут быть равны 0'); //входные данные "ограничены", поэтому если пользователь return; //введет их неправильно, то ему придётся ввести данные ещё раз, но на этот раз правильно } if ((H1 < 0) || (H2 < 0) || (p1 < 0) || (p2 < 0)) { alert('Входные данные не могут быть меньше 0'); return; } if (H2 < H1) { alert('H2 должно быть больше H1'); return; } var p1 = document.forma1.t4.value; var p2 = document.forma1.t5.value; var L = H2 - l1 * (p1 / p2 || 0); document.forma1.res.value = L; } function calc1() { //в подрасчёте есть промежуточное значение l1 console.log(1); //пользователь узнает чему равно l1, только после ввода H1 и H2, и нажатия на var H1 = +document.forma1.t1.value || 0; //текстовое поле t3 var H2 = +document.forma1.t2.value || 0; var l1 = H2 - H1; document.forma1.t3[0].value = H1; document.forma1.t3[1].value = H2; document.forma1.t3[2].value = l1; } document.addEventListener("DOMContentLoaded", function(event) { document.forma1.t1.addEventListener("keyup", calc1); document.forma1.t2.addEventListener("keyup", calc1); }); /* демо вычисления */ $(function(){ $("#demo").click(function(){ var H1 = $(".h1").attr("data"); var H2 = $(".h2").attr("data"); var L1 = H2-H1; var Pup = $("#pup").attr("data"); var Pzh = $("#pzh").attr("data"); var L = H2-L1*(Pup/Pzh); $(".h1").val(H1); $(".h2").val(H2); $(".l1").val(L1); $("#pup").val(Pup); $("#pzh").val(Pzh); $("#l").val(L); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form name="forma1" style="background-color:#44944A;"> <!-- поменяю цвет формы --> <div id="resizable"> <!--"подрасчёт 1.1"--> <table align="center"> <br> <p align="center">Глубина установки конца заливочных труб</p> <tr> <td height="40px"> <div class="price" title="H1">Расстояние от устья скважины до нижних отверстий фильтра, м;</div> <input name="t1" type="text" align="right" size="4" maxlength="8" onkeyup="return proverka(this)" id="t3" class="h1" data="4550"> </td> </tr> <tr> <td height="40px"> <div class="price" title="H2">Расстояние от устья скважины до верхних отверстий фильтра, м;</div> <input name="t2" type="text" align="right" size="4" maxlength="8" onkeyup="return proverka(this)" id="t3" class="h2" data="4566"> </td> </tr> <tr> <td height="40px"> <div class="price">Интервал отверстий фильтра, м;</div> <input name="t3" type="text" align="right" size="4" maxlength="8" onkeyup="return proverka(this)" id="t3" class="l1"> </td> </tr> <tr> <td height="40px"> <div class="price">Плотность цементного раствора, кг/м<sup>3</sup>;</div> <input name="t4" type="text" align="right" size="4" maxlength="8" onkeyup="return proverka(this)" id="pup" data="1800"> </td> </tr> <tr> <td height="40px"> <div class="price">Плотность жидкости, находящейся в скважине, кг/м<sup>3</sup>;</div> <input name="t5" type="text" align="right" size="4" maxlength="8" onkeyup="return proverka(this)" id="pzh" data="1080"> </td> </tr> <tr> <td> <input type="button" name="button" value="Вычислить" onClick="areaRectangle();"> <input type="button" name="button" value="Вычислить Демо" id="demo"> <input type="text" name="res" size="10" id="l"> </td> </tr> </table> </div> <br> </form> 

  • Thank you, it works on your site, but nothing happens on my denwer when you click on the "Calculate Demo" button, as if it ignores it (I did not change the code, only your one inserted). - Ram
  • I added a function to the script, hooked jqery into html and added some styles to the input. Check or connect jqery: <script src = " ajax.googleapis.com/ajax/libs/jquery/2.1.1/… >. If you have copied everything into your project, it should work. - Dmitriy Kondratiuk
  • Thank you, corrected, but now it looks a bit different, he supposedly thinks not 4550 -..., but 4566 -... Ok, not the point, but most likely there was a typo in the textbook - Rem
  • There in the tutorial is definitely a mistake. In the picture, look in the formula where the calculation method is written H2, and in the formula where the calculation itself takes place is the value of H1. Specify this moment at the one who gave you the task - Dmitriy Kondratiuk
  • There is a question how in this script to round off, for example, to hundredths, the result is L $ (function () {$ ("# demo"). Click (function () {var H1 = $ (". H1"). Attr ("data") ; var H2 = $ (". h2"). attr ("data"); var L1 = H2-H1; var Pup = $ ("# pup"). attr ("data"); var Pzh = $ (" #pzh "). attr (" data "); var L = H2-L1 * (Pup / Pzh); $ (". h1 "). val (H1); $ (". h2 "). val (H2) ; $ (". l1"). val (L1); $ ("# pup"). val (Pup); $ ("# pzh"). val (Pzh); $ ("# l"). val ( L);});}); - Ram