Запустите JavaScript функции, когда пользователь нажимает ввод - PullRequest
0 голосов
/ 02 апреля 2020

Я создал калькулятор с указанными c свойствами в HTML, и я хотел бы, чтобы пользователь мог нажимать клавишу ввода, чтобы отобразить оба значения display1() и display2().
Другими словами, я хочу, чтобы клавиша ввода вызывала кнопку Both.

Вот код, который у меня есть, и то, что я пытался до сих пор пытаться добавить:

<!DOCTYPE html>
<html>
    <head>
        <title>Square Yards Calculator</title>
    </head>

    <body>
        <div id='calc-contain'>

          <form name="calculator">

            <input type="text" name="answer" />
            <br>

            <input type="button" value=" 1 " onclick="calculator.answer.value += '1'" />
            <input type="button" value=" 2 " onclick="calculator.answer.value += '2'" />
            <input type="button" value=" 3 " onclick="calculator.answer.value += '3'" />
            <input type="button" value=" + " onclick="calculator.answer.value += '+'" />
            <br/>

            <input type="button" value=" 4 " onclick="calculator.answer.value += '4'" />
            <input type="button" value=" 5 " onclick="calculator.answer.value += '5'" />
            <input type="button" value=" 6 " onclick="calculator.answer.value += '6'" />
            <input type="button" value=" - " onclick="calculator.answer.value += '-'" />
            </br>

            <input type="button" value=" 7 " onclick="calculator.answer.value += '7'" />
            <input type="button" value=" 8 " onclick="calculator.answer.value += '8'" />
            <input type="button" value=" 9 " onclick="calculator.answer.value += '9'" />
            <input type="button" value=" Flex61 "   onclick="display1()" />
            </br>

            <input type="button" value=" c " onclick="calculator.answer.value = '',
                                document.getElementById('printhere1').innerHTML= '',
                                document.getElementById('printhere2').innerHTML= ''" />

            <input type="button" value=" 0 " onclick="calculator.answer.value += '0'" />
            <input type="button" value=" Both " onclick="display1(),display2()" />
            <input type="button" value=" Gap55 "    onclick="display2()" />
            </br>


          </form>
          <div id="agh">
            <p>Enter how many Square yards (SY) you are covering</p>
            <p id="printhere1"></p>
            <p id="printhere2"></p>
          </div>
        </div>

        <script type="text/javascript">
          function display1(){
            //Assigning the variable to the user input
            var squareyards = eval(calculator.answer.value);
            if (squareyards < 0 || squareyards == null){
                squareyards = 0
            }
            var pounds = 5
            pounds = squareyards * pounds
            // to print the input here
            document.getElementById("printhere1").innerHTML = "For "+ squareyards + " SY sou need: "+ pounds + " lbs of Elasto Flex61";
            }

            function display2(){
                //Assigning the variable to the user input
                var squareyards = eval(calculator.answer.value);
                if (squareyards < 0 || squareyards == null){
                    squareyards = 0
                }
                var rolls = 9
                rolls = Math.ceil(squareyards * rolls / 103)
                // to print the input here
                document.getElementById("printhere2").innerHTML = "For "+ squareyards + " SY sou need: "+ rolls + " Rolls of Gap55 Smooth";
            }
            $(function(){  
                $(':text').bind('keydown',function(e){ //on keydown for all textboxes  
                    if(e.keyCode==13){ //if this is enter key  
                        e.preventDefault();
                        e.display1();
                        e.display2();
                    }             
                });               
            });  

        </script>

    </body>
</html>

1 Ответ

0 голосов
/ 02 апреля 2020

Ты почти у цели. Похоже, у вас есть смесь родных JavaScript, document.getElementById и jQuery для функциональности нажатия клавиш. jQuery не требуется, поэтому я бы порекомендовал просто использовать нативный JavaScript для всего.

Поэтому я бы поменял этот бит:

$(function(){  
    $(':text').bind('keydown',function(e){ //on keydown for all textboxes  
        if(e.keyCode==13){ //if this is enter key  
            e.preventDefault();
            e.display1();
            e.display2();
        }             
    });               
});

Чтобы быть нативным JavaScript:

// Capture enter button event on entire page
document.addEventListener('keydown', getAnswer);

// I made it a separate function in case you want to re-use
function getAnswer(e) {
    if (e.keyCode==13) { //if this is enter key  
        e.preventDefault();
        display1();
        display2();
    }             
}

Вот рабочий codepen .

Однако это только первый шаг, чтобы заставить его работать. Как было сказано в @ sureperformance, следующим шагом будет удаление document.getElementById s из кнопки «Очистить» при нажатии и перемещение их в отдельную функцию.

Надеюсь, это поможет.

...