javascript - Linking keys to code -
i'm quite new programming (started yesterday) , far i've created simple code. unaware on how make can click enter , submit forum post commands on how make possible appreciated :)
<!doctype html> <html> <head> <title>title changing simulator!</title> <script type="text/javascript"> function substitute() { var myvalue = document.getelementbyid('mytextbox').value; if (myvalue.length == 0) { alert('please enter real value in text box!'); return; } var mytitle = document.getelementbyid('title'); mytitle.innerhtml = myvalue; } </script> </head> <body> <h1 id="title">title changing simulator!</h1> <input type="text" id="mytextbox" /> <input type="submit" value="click button" onclick="substitute()" /> </body> </html>
wrap input , button in <form>
, listen form's submit event triggered either clicking submit button or pressing enter in input field. see how trigger enter key press of textbox?
const form = document.getelementbyid('form'); const text = document.getelementbyid('text'); const title = document.getelementbyid('title'); form.addeventlistener('submit', event => { event.preventdefault(); if (text.value.length > 0) { title.textcontent = text.value; } else { alert('please enter real value in text box!'); } });
<h1 id="title">title changing simulator!</h1> <form id="form"> <input type="text" id="text"> <input type="submit" value="update"> </form>