I'm working on a user control to display a chat box for Dialogflow and I want enter to submit the string entered in the box to a JavaScript event instead of the code behind. I want to be able to add this user control to any of my .net pages, which contain buttons and inputs of their own. Unfortunately, this requirement prevents me from taking the easy route and disabling the enter key submit behavior in the form.
Here is the HTML for the control:
<div id="mainWrapper">
<div id="result">
</div>
<div id="inputField">
<input placeholder="Ask me a question" id="query" type="text" />
</div>
<asp:HiddenField ID="access" runat="server" />
</div>
The only thing I currently have my code behind doing is assigning a value to that hidden field on page load. I have tried changing the input to asp:TextBox
, and adding UseSubmitBehavior="False"
, but it still causes a postback. I have also added return false;
to the JavaScript I am using, but it seems like the postback occurs before it runs.
Here is the relevant JavaScript:
(function () {
"use strict";
var token, queryInput, resultDiv;
var ENTER_KEY_PRESS = 13;
var client;
window.onload = init;
function init() {
token = document.getElementByID("<%= access.ClientID %>").value;
queryInput = document.getElementById("query");
resultDiv = document.getElementById("result");
queryInput.addEventListener("keydown", keyDown);
}
function keyDown(event) {
if (event.which === ENTER_KEY_PRESS) {
console.log("Enter pressed")
var queryValue = queryInput.value;
queryInput.value = "";
sendTextToDIalogflow(value)
.then(function (response) {
var result;
try {
result = response.result.fulfillment.speech;
} catch (error) {
result = "error: " + error.message;
}
console.log(result)
})
.catch(function (err) {
console.log("Whoops, something went wrong: " + err.message);
});
}
else {
console.log("Enter not pressed")
}
}
return false;
})();
How do I prevent the enter key from triggering a postback when the cursor is in the textbox without doing the same for other asp.net controls on the page?