简体   繁体   中英

How to listen to press submit button in HTML page

This script emits the text-entered after the user press the enter key. What I need is to listen to click on the submit button in my HTML page. This is the script:

// When the user hits return, send the "text-entered"
// message to main.js.
// The message payload is the contents of the edit box.
var textArea = document.getElementById("txt-field");
textArea.addEventListener('keyup', function onkeyup(event) {
  if (event.keyCode == 13) {
    // Remove the newline.
    text = textArea.value.replace(/(\r\n|\n|\r)/gm,"");
    addon.port.emit("text-entered", text);
    textArea.value = '';
  }
}, false);

The HTML is:

<html>
<head>
    <style type="text/css" media="all">
      textarea {
        margin: 10px;
      }
      body {

        background-color:#b3dbfa;
      }
    </style>
  </head>

  <body>

  <form> 
      Enter URL: <br>
      <input type="text" id="txt-field">
      <input type="submit" value="Add">
  </form>
  <script src="get-text.js"></script>
  </body>
</html>

Looks like you're using the Addon-On SDK which is a legacy technology. Mozilla reccomends migrating to WebExtensions.

However to answer your question: With jquery you could do something like

$('#myform').submit(function(e) {
    e.preventDefault(); // don't submit
    console.log('do something');
});

With pure javascript you could do something like

var form = document.getElementById('myform');
form.addEventListener('submit', function(e) {
    e.preventDefault(); // don't submit
    console.log('do something');
})

To listen to clicks in the submit button, simply, in the script, add an event listener to the submit button. But first, add and id to the submit button in the HTML:

<input type="submit" value="Add" id="submit-btn">

In the script:

addbtn=document.getElementById("submit-btn");
addbtn.addEventListener('click', function (event) {
event.preventDefault();
// Get the text and remove the newline.
var text = formTextArea.value.replace(/\s/,"");    //remove space characters
var level = document.getElementById("levels-list").value;
//send the entered data to the addon to store them
self.port.emit("text-entered", text);
                                                        self.port.emit("selected-level", level);
formTextArea.value = ''; //intialise the text area to empty after adding the item.
}
,false);

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