简体   繁体   中英

i would like to use return on a form and want to know how to use return key on a button

I want to assign the return key to 'button' as well as 'click' on a mouse. Please help.

  var input = document.querySelector('input');
  var btn = document.querySelector('button');
  var para = document.querySelector('p');
  btn.addEventListener('click', function() {
    var code = input.value;
    para.textContent = eval(code);
  });

Add keyup event listener on your field

  var input = document.querySelector('input'); var btn = document.querySelector('button'); var para = document.querySelector('p'); function run() { var code = input.value; para.textContent = eval(code); } btn.addEventListener('click', run); input.addEventListener('keyup', function(e) { if(e.keyCode === 13) run() }) 
 <input> <button>Eval</button> <p></p> 

You need to use addEventListener to bind the keyup event to the input. e.keyCode == 13 will check if the key pressed is enter, whose key code is 13. It will then execute the code.

 var input = document.querySelector('input'); var btn = document.querySelector('button'); var para = document.querySelector('p'); btn.addEventListener('click', function() { var code = input.value; console.log(code) para.textContent = eval(code); }); input.addEventListener('keyup', function(e) { if (e.keyCode == 13) { var code = input.value; console.log(code) para.textContent = eval(code); } }) 
 <input type="text"> <button type="button">Submit</button> <p>Result</p> 

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