Search code examples
javascriptfirefox-addonfirefox-addon-sdkdom-events

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>

Solution

  • 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);