I am developing an add on using mozilla's add-on sdk. I have a panel attached to a toggle button that contains one input text box and a submit button. When the user presses enter, I am able to get my function to work. However, when I press the submit button nothing happens. Why is this? I have attached my code below:
// 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("numTimes");
textArea.addEventListener('keyup', function onkeyup(event) {
if (event.keyCode == 13) {
// Remove the newline.
text = textArea.value.replace(/(\r\n|\n|\r)/gm,"");
self.port.emit("text-entered", text);
textArea.value = '';
console.log("Got text from enter");
}
}, false);
// Listen for the "show" event being sent from the
// main add-on code. It means that the panel's about
// to be shown.
//
// Set the focus to the text area so the user can
// just start typing.
self.port.on("show", function onShow() {
textArea.focus();
});
var submit = document.getElementById("search");
submit.addEventListener("click", function submit(){
text = textArea.value.replace(/(\r\n|\n|\r)/gm,"");
self.port.emit("text-entered", text);
textArea.value = '';
console.log("Got text from submit button");
}, false);
The code that's within the textArea section works but the code by the submit section doesn't. Does JavaScript treat these differently?
Related
There is an input box for entering number and dumping to the page of a PDF .
user will put the page number in input box and press" enter "on keyboard
i need to Simulate Enter on keyboard in JavaScript.
i tried the following , but it didnt jump to the page i want .
var event = document.createEvent("HTMLEvents");
event.initEvent("change", true, true);
event.eventName = "change";
document.getElementById('input').dispatchEvent(event);
var event = document.createEvent("HTMLEvents");
event.initEvent("keydown", true, true);
event.eventName = "keydown";
document.getElementById('input').dispatchEvent(event);
You can try as per below:
var input = document.getElementById("input");
// Execute a function when the user releases a key on the keyboard
input.addEventListener("keyup", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the action you want for eg; below code will do the button click action
document.getElementById("myBtn").click();
}
});
Hope it helps your problem.
it's my first time using the submit event on a form. Rather than submitting, I have used preventDefault() and then added some code to execute a search. When I press the search button, it works properly, creating a div where it loads the search results. When I press enter, it works properly up to the point where it has to append the new div to the html.
This is the function that creates the div
const crearDivResultados = function() {
const divResultados = document.createElement('div');
divResultados.setAttribute("id", "resultados");
contenedorResultados.append(divResultados);
}
This is the rest of the code.
const formulario = document.forms.buscador
formulario.addEventListener('submit', (event) => {
event.preventDefault();
let inputValor = inputBusqueda.value;
contenedorResultados.innerHTML = '';
crearTitulo(inputValor, contenedorResultados);
crearDivResultados();
let resultados = document.querySelector('#resultados');
console.log(resultados);
buscarGifs(inputValor).then (resp => {
mostrarResultados(resp.data);
})
botonBusquedaDesplegado.style.display = 'none';
contenedorResultados.style.display = 'block';
resultados.style.display = 'flex';
})
The error (Uncaught (in promise) ReferenceError: resultados is not defined) appears in this line of code:
let resultados = document.querySelector('#resultados');
ONLY when submitting with enter key. When clicking the button it works just fine.
Thank you!!!
Event type Submit means the submit button is clicked. If you want to listen to another event type, use keypress
So for accessibility purposes I am trying to captured tabbed focus and blur events to capture tab order within a modal.
For some reason I am running into some odd browser behavior.
Inside my component I have the following code:
// On Init
ngOnInit (){
// Get all of the buttons and anchors in the modal
var buttons = this.modal.nativeElement.querySelectorAll("button, a");
// Get the number of buttons
var numButtons = buttons.length;
// Get the last button
var lastButton = buttons[numButtons - 1];
// When the last button loses focus
lastButton.addEventListener("blur", (e: any) => {
// Prevent Default
e.preventDefault();
// Focus on the modals close button
this.focusCloseButton();
})
}
And TECHNICALLY this works perfectly. If I log out the active element after the call to this.focusCloseButton, I indeed get a reference to the close button.
HOWEVER, the tab actually moves to the browser itself into whatever the first element is. For Chrome this is the "View site information" button to the left of the URL bar. In Firefox this is the first tab in the list of tabs.
How can I capture this properly so that the browser is not hijacking the tab press?
Apparently the blur event happens too late to be captured before the browser takes over.
Instead I used keybinding to detect when the tab-key was pressed and did the capturing from there.
// The OnInit function handles capturing tab order
ngOnInit (){
// All of the buttons and links in the modal
var buttons = this.modal.nativeElement.querySelectorAll("button, a");
// The first button or link in the modal
var firstButton = buttons[0];
// The last button or link in the modal
var lastButton = buttons[buttons.length - 1];
// Listen for keydown events on the modal
this.modal.nativeElement.addEventListener("keydown", (e: any)=> {
// If the key pressed was the tab button
if ( e.keyCode === 9 && !e.shiftKey ) {
// If the currently active element is the last button
if (document.activeElement == lastButton){
// Prevent default action
e.preventDefault();
// Put focus on the close button
this.focusCloseButton();
}
} else if ( e.keyCode === 9 && e.shiftKey === true ){
// If the key pressed was shift+tab
// And the currently active button is the close button
if ( document.activeElement == firstButton ){
// Prevent Default
e.preventDefault();
// Focus the last button
lastButton.focus();
}
}
})
}
for those wondering about what this.focusCloseButton does:
// Puts focus on the close button
focusCloseButton: Function = function(){
this.closeButton.nativeElement.focus();
};
The reference to closeButton is created by ViewChild:
// Reference to the close button
#ViewChild("closeButton") closeButton: ElementRef;
Which ties into the dom with the marked element:
<button #closeButton></button>
Pressing the tab key which triggers a focus change is also received by the input receiving the focus as a keyup.
a: <input type='text'/><br/>
b: <input type='text' onkeyup='alert("wtf?")'/><br/>
http://jsfiddle.net/59SnP/
As my control also uses tab (not in the example), I would want the focus related keyup event being consumed (but I want to receive other non-focus-change related tab events). I tried to research the rationale behind the current behavior but found nothing. The question: Where is this current behavior specified (event not consumed by focus change), and what would be a cross-browser workaround to force consuming it. Thx.
You can try this. I changed your keyup event in your input :
<input type='text' onkeyup="if(!tabPressed){ alert('This is it !'); }"/>
And I added a little event handler which will raise a flag when the tab button is pressed :
var tabPressed = false;
document.addEventListener('keydown', function (e) {
if(e.keyCode == 9) {
tabPressed = true;
} else {
tabPressed = false;
}
}, false);
Based on Nathan's insight, here is a fully working example:
// First part of Nathan's HACK (set a sentinel when a focus changing tab has happened)
var tabPressed = false;
// remove this listener to break the functionality
$(document).on("keydown", function (e) {
if(e.keyCode == 9) {
tabPressed = true;
} else {
tabPressed = false;
}
});
// The listener on the client input that would kill the keyup tab event upon focus change
$("#magic").on("keyup", function(e) {
if (tabPressed && e.keyCode==9) {
tabPressed = false; // reset the sentinel
e.stopImmediatePropagation()
e.preventDefault()
}
})
And here is the second part, which is a simple skeleton of something meaningful. We disable TAB inside the input, and log it as we do with other keyups:
$("#magic").on("keydown", function(e) {
if (e.keyCode==9) {
e.preventDefault()
e.stopPropagation()
}
})
$("#magic").on("keyup", function(e) {
$(this).val($(this).val() + " " + e.keyCode)
e.stopPropagation()
e.preventDefault()
})
The HTML backing the story is as simple as:
a: <input type='text'/><br/>
b: <input type='text'/><br/>
c: <input type='text' id='magic'/><br/>
If you want to play with it, here it is on jsfiddle
NOTE: This still is not the perfect solution, the sentinel is just reset inside the control, so if a tabpress moving the focus does not activate our input, the sentinel stucks, and the first event will be swallowed.. So here is an example of wrong behaviour:
Click on input A
Press TAB (focus moves to input B, tabPressed becomes true)
Click on input C
Press TAB (it is eaten up as sentinel is true)
Press TAB (now it goes through)
Still it is slightly better to have to press TAB twice as to have something happening automatically, wo user control...
I have a text box for typing names inside a form.A div below the text box shows names of registered users from the database with the help of AJAX starting with the letters typed by the user.The user can also click on the usernames and those names will be placed in the text box.Also the div will get disappear.I have written onblur event for the text box so that on losing the focus for the text box,the div created below should disappear.This works for me.My issue is that i cant select the names from the div below ,since on blur event fires.I need onblur event because all other events other than selecting username function requires this on blur event.
My code is like this:
<input id="venue" type="text" onkeyup="showData(this.value)"
onblur="return removediv()"/>
<div id="venuesearch">
</div>//div for displaying the set of usernames with help of AJAX
My javascript code is:
function showData(str)
{
if (str.length==0)
{
document.getElementById("venuesearch").innerHTML = "";
document.getElementById("venuesearch").style.border = "0px";
return;
}
// some AJAX code here
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("venuesearch").innerHTML=xmlhttp.responseText;
document.getElementById("venuesearch").style.border="1px solid #A5ACB2";
document.getElementById("venuesearch").style.display="block";
document.getElementById("venuesearch").style.overflow="show";
}
xmlhttp.open("GET","search_venue.php?venue="+str,true);
xmlhttp.send();
}
Inside search_venue.php
There is a method called showVal() on onClick event of the column .
function showVal(val)
{
document.getElementById("venue").value = val;
document.getElementById("venuesearch").style.display = "none";
}
function removediv()
{
document.getElementById("venuesearch").style.display="none";
return false;
}
try this :
function removediv()
{
document.getElementById("venuesearch").style.display="none";
var venue = document.getElementById("venue").value;
return false;
}