I am trying to simulate a Keyboard event with jquery. What I want is when I click a button, I want a character to appear in a textarea. I need the action to be a keyboard simulation not a simple append. I have tried all the possible solutions on the web without any success, so I would be grateful if anyone can help me.
Here is my HTML/JS/Jquery code :
<html>
<head></head>
<body>
<script type='text/javascript' src='jquery-1.9.1.min.js'></script>
<input type='text' id="input"></input>
<script type='text/javascript'>
function simulateKeyPress() {
document.getElementById("text").focus();
var e = $.Event("keypress");
e.which = 97;
$("input").trigger(e);
}
</script>
<br/>
<button id="button" onclick='simulateKeyPress()'>Press Me</button>
</body>
</html>
As you can see, when the button is clicked, I only get a focus on the text element, but no character appears, any ideas?
looks like I was not clear enough. Here is another sample, I am using the MouseTrap library to capture keyboard events.
Here is my code.
<html>
<header>
<title>test</title>
</header>
<script type='text/javascript' src='MouseTrap.js'></script>
<script type='text/javascript' src='jquery-1.9.1.min.js'></script>
<body>
<input type='text' class="mousetrap" id="input"></input>
<script type='text/javascript'>
Mousetrap.bind('4', function(){alert("you pressed 4" );});
function simulateKeyPress(character) {
document.getElementById("input").focus();
var input = $('#input');
input.val(input.val() + character);
}
</script>
<br/>
<button type="button" onclick='simulateKeyPress(4)'>Press Me</button>
</body>
</html>
With this code, whenever you press '4' on the keyboard, an alert box will appear. All I want is when I click the button, the same event to be created. Ideas?
Here is one solution to simulate the keypress :
var input = $('#input');
$('#button').click(function(){
// Add a character to the input
input.val(input.val() + 'x');
// Trigger the keypress event
input.keypress();
});
// Check if it work
input.on('keypress', function(){
alert('key pressed!');
});
Here is a jsfiddle demo.
Javascript does not perform default actions when you fire it from javascript. So the only way is to create your own vent handler :
function simulateKeyPress() {
document.getElementById("text").focus();
var e = $.Event("keypress");
e.which = 97;
$("input").trigger(e);
}
$("input").on('keypress', function(e){
//append e.which to your input here
});
It doesn't seem possible to acheieve this without appending the characters manually to the textarea.
The answers that #HighKickX and #claustrofob wrote only triggers the event handler as if the specificed key was pressed, but not actually presses that key like happens when a key is pressed on the keyboard (probably due to security reasons).
Because only the event is fired but the key is not actually pressed the textarea won't have that character added automatically.
try this
<input id="field">
<button id="x" class="button">submit</button>
$(".button").click(function() {
var value = $("#field").val();
$("#field").val( $("#field").val() + value);
});
Related
To reproduce the issue, use the fiddle at [1] and follow these steps:
Click on text box
Input some value in it
After value input, click of the "click me" button. Please Note, don't click anywhere else on the browser
You would see the "button click" event not getting triggered.
The HTML code looks like this,
<div class="wrapper">
<input type="text" id="input"/>
<div class="error">There is an error </div>
</div>
<button type="button" id="button">Click Me</button>
<div id="log">Logs</div>
The JavaScript code for the same is:
$(function () {
$("input,button").on("click focus blur mousedown mouseup", function (e) {
$("#log").append($("<div/>").html(e.target.id + " " + e.type))
var self = this
if (self.id === "input" && e.type=="blur") {
$(self).trigger("exit")
}
})
$(".wrapper").on("exit", function () {
$(this).find(".error").hide()
$(this).find(".error").text("")
})
})
The issue is reproducible in "Chrome" and "firefox". Is this a know bug in "Chrome" or anyone who have faced any similar issue ?
Ideally, the click event on button has to be triggered but somehow it doesn't ? I am not able to understand the cause or a possible fix.
I don't want to use the setTimeout() to defer the "blur" event execution
[1] https://jsfiddle.net/cg1j70vb/1/
This is happening since on blur of the input you are removing the error text. That shifts the button up (possibly DOM re-paint) and hence misses the click
I removed the error message and it works fine.
$(function() {
$("input,button").on("click focus blur mousedown mouseup", function(e) {
$("#log").append($("<div/>").html(e.target.id + " " + e.type))
if (this.id === "input" && e.type == "blur") {
$(this).trigger("exit")
}
})
$(".wrapper").on("exit", function() {
$(this).find(".error").hide()
$(this).find(".error").text("")
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<input type="text" id="input" />
</div>
<button type="button" id="button">Click Me</button>
<div id="log">Logs</div>
I think its because the hide() function of your error message.
I tried to remove it and just replace the error message and it works.
Demo
$("input").focus(function(){
console.log('input focused');
});
Above is my code to test if focus event happened.And I made a button to insert another input dynamically.But while I focus the inserted inputs,no console logged at all.
Can anybody help?
Thanks
You need to use event delegation with the focusin event as focus does not support bubbling(event delegation requires bubbling support to work).
$("input").focus(function() {
snippet.log('input focus: ' + $('input').index(this));
});
$('#dynamicarea').on('focusin', 'input', function() {
snippet.log('input focusin: ' + $('input').index(this));
});
$('button').click(function() {
$('div').append('<input />');
})
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input />
<input />
<input />
<br />
<button>Add</button>
<div id="dynamicarea"></div>
function focused(evt){
var target = evt.target;
var target_name = evt.target.nodeName;
$(target).keydown(function(e){
if(e.which==9 && $(e.target).parent().parent().is(":last-of-type")){
e.preventDefault();
}else{
$(this).unbind("keydown");
}
});
}
<sectionA>
<input>
/*insert input here*/
</sectionA>
<sectionB>
<input>
<input>
</sectionB>
Originally I was trying to stop focusing to the next input in the sectionB which is not in the viewport when pressing the tab. So I write a function above to bind in the inserted input to tell. But Arun's answer also work. Thanks a lot.
I have a blur event in a textarea:
$("#question-id-5-answer").blur(function (event) {}
And a click event in the Submit button:
$("#" + _sendBtnId).on("click", function () {}
It happens that the Click event does not fire because the Blur event cancel the click event.
I can't use the Mousedown event because it's a touch device that does not detect it.
I tried saving the following on my mobile device as a htm file and accessed using Forefox application. Appears to be working as expected. Please have a look if it helps you.
<form id="myForm">
<textarea id="myTxt"></textarea>
<input type="button" id="butSubmit" value="Submit" />
</form>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function() {
$("#myTxt").blur(function() {
if($(this).val() != "") {
alert("retunging false");
return false;
}
alert("rextarea is empty");
});
$("#butSubmit").click(function() {
alert("submitted");
});
});
</script>
here is my code
<html>
<head>
<script type="text/javascript">
window.onload = function(){
sel = document.getElementsByTagName('select');
for(i=0;i<sel.length;i++)sel[i].onclick = function(){alert('');}
}
</script>
</head>
<body>
<div id="ss"></div>
<select></select>
<input type="button" onclick="document.getElementById('ss').appendChild(document.createElement('select'))"/>
</body>
</html>
"onclick" event working for static tag "Select" but not working for Dynamically created "Select". In other word i want to know what is alternate to .live of JQuery in Javascript.
Bind the event to a parent element, that already exists in the DOM:
document.body.addEventListener('click', function (e) {
if (e.target.tagName.toLowerCase() == 'select') {
alert('You clicked a select!');
}
});
JS Fiddle demo.
It would be slightly more sensible to bind the click to an element 'closer' to the form, and if you use getElementById() rather than getElementByTagName() it's more simple, since you don't have to worry about the index of the number you're binding to.
jQuery's live function works by using "Event Delegation". The basic idea is that you bind a listener on a parent element, which is guaranteed to exist when the page loads. Any element below that (with the exception of some) will fire off an event which can be caught by the parent listener. From there you would need to retrieve the target/sourceElement of the event and determine whether or not it's one you care about.
Something like this will work for listening to clicks. Just make sure that any new elements you are adding are located within the proper parent container and have an attribute which distinguishes them from the rest of the clickable elements.
<html>
<head>
<script type="text/javascript">
window.onload = function(){
// get the relevant container
var eventContainer = document.getElementById("EventContainer");
// bind a click listener to that container
eventContainer.onclick = function(e){
// get the event
e = e || window.event;
// get the target
var target = e.target || e.srcElement;
// should we listen to the click on this element?
if(target.getAttribute("rel") == 'click-listen')
{
alert("You clicked something you are listening to!");
}// if
};
};
</script>
</head>
<body>
<div id="EventContainer">
<input type="button" rel="click-listen" name="myButton" value="Listening to this button." />
<input type="button" name="anotherButton" value="Not listening." />
<p>I'm also listening to this a element: listening to this</p>
</div>
</body>
</html>
there's no need to bind the onclick handler to every select every time you add one.
I am not going to retype your whole page, but you'll see what's going on by reading following snippets:
function handler() {
alert('You clicked a select!');
}
window.onload = function(){
sel = document.getElementsByTagName('select');
for(int i= 0; i < sel.length; i++) {
sel[i].onclick = handler;
}
}
function addSelect() {
var slt = document.createElement("select");
document.getElementById('ss').appendChild(slt);
slt.onclick = handler;
}
<input type="button" onclick="addSelect();"/>
You're only setting the onclick when the window loads. All you need to do is put the code currently in the window.onload into a named function, then call it every time you add a new select.
here's the dumb way to do it:
<html>
<head>
<script type="text/javascript">
function update () {
sel = document.getElementsByTagName('select');
for(i=0;i<sel.length;i++)sel[i].onclick = function(){alert('');}
}
window.onload = update;
</script>
</head>
<body>
<div id="ss"></div>
<select></select>
<input type="button" onclick="document.getElementById('ss').appendChild(document.createElement('select'));update();"/>
</body>
</html>
You can use a cross-browser solution as shown below to add event handler dynamically
sel = document.getElementsByTagName('select');
for( i=0; i<sel.length; i++){
if (sel[i].addEventListener){
sel[i].addEventListener("click", clickHandler, false);
} else if (sel[i].attachEvent){
sel[i].attachEvent("onclick", clickHandler);
}else{
sel[i].onclick = clickHandler;
}
}
function clickHandler(event){
}
Why wouldn't onChange function of an input be activated when the value of the input is changed by javascript? For example why when clicking on the button alert wouldn't happen?
<html>
<body>
<input type="text" id="myInput" onchange="alert(1)" />
<button onclick = "document.getElementById('myInput').value = 'ads'">click</button>
</body>
</html>
How can I make the onchange function work then?
edit:
I now understand event won't be triggered automatically, how can I call it(jquery too) ?
Scripted value changes don't trigger an event. You have to manually trigger an event.
jQuery: $('#myInput').trigger('change');
Add the following code to the onchange event:
var input = document.getElementById("myInput");
if(input.fireEvent) input.fireEvent("onchange");
else {
var ev = document.createEvent('HTMLEvents');
ev.initEvent("change", true, false);
input.dispatchEvent(ev);
}
So, combined with your code (you should actually separate the JS code from the HTML):
<button onclick="var input = document.getElementById('myInput');input.value = 'ads';if(input.fireEvent)input.fireEvent('onchange');else{var ev=document.createEvent('HTMLEvents');ev.initEvent('change',true,false);input.dispatchEvent(ev);}">click</button>