I know this is a really simple question, but how do I add content to a div when the user types into a input field and hits enter?
I have tried:
document.addEventListener('keydown', function(e){
if(e.keyCode === 13) {
function bleh() {
var from = document.getElementById('setter').value;
x = document.getElementById("mything");
x.innerHTML = from;
}
}
})
my HTML is:
<input type="text" autofocus="autofocus" id="setter"
onkeydown="writeit(this, event);moveIt(this.value.length, event)"
onkeyup="writeit(this, event)" onkeypress="writeit(this, event);"></input>
if you want to see it in action, go to thomaswd.com/cmd. start typing and hit enter.
again, this sounds like a really simple question, but I cant get it working. Thanks!!!
You were really close:
document.getElementById("setter").addEventListener('keydown', function(e){
if(e.keyCode === 13) {
var from = this.value;
x = document.getElementById("mything");
x.innerHTML = from;
}
})
JSFiddle: http://jsfiddle.net/9bbR2/
Although I would recommend using jQuery, it's much simpler.
$(function() {
$("#setter").keydown(function(e) {
if(e.keyCode === 13) {
$("#mything").text($(this).val());
}
});
});
Related
First time we press keyboard enter key should execute button(id="botonCorregir"). But the second time we press enter key should execute url().
I use cont, for the first time execute one part of the javascript code, and after when de cont value is 1, execute the second part of javascript code.
For some mistake, it doesn´t work.
thanks!
HTML:
<input id="respuestaUsuario"></input>
<button id="botonCorregir">Reply</button>
<a id="enlaceSiguiente" href="nextQuestion.html">Next question</a>
JAVASCRIPT:
<script>
var cont=0;
if(cont==0){
//Should enter the first press of enter
var input = document.getElementById("respuestaUsuario");
console.log('input: ', input)
input.addEventListener("keyup", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
document.getElementById("botonCorregir").click();
}
});
cont++;
}else{
//Should enter the second press of enter
if (event.keyCode == 13) {
event.preventDefault();
document.getElementById("enlaceSiguiente").click();
}
}
</script>
You have a few mistakes in the code.
You are assigning the event based on the value of cont so always will have that functionality. Javascript does not re-interpret the code once the value of cont is changed.
I mean, Javascript check only one time the condition:
if(cont==0){}
This is a solution that works:
var cont=0;
var input = document.getElementById('respuestaUsuario');
input.addEventListener('keyup', function (event) {
event.preventDefault();
if (event.keyCode == 13) {
if(!cont){
alert('uno');
document.getElementById("botonCorregir").click();
cont++;
}else{
document.getElementById("enlaceSiguiente").click();
}
}
});
I guess you were on the right track, but the problem is that your Javascript only gets executed once. So, the else case will never be triggered. I refactored your code to use the check in the event listener:
var cont = 0;
var input = document.getElementById("respuestaUsuario");
input.addEventListener("keyup", function (event) {
if (event.keyCode == 13) {
event.preventDefault();
if (cont == 0) {
cont++;
document.getElementById("botonCorregir").click();
} else {
document.getElementById("enlaceSiguiente").click();
}
}
});
I also created a codepen for you to check out.
I am using code to make the spacebar do something for an HTML 5 game. It works great, but the page that displays the game also has a Search Box, and visitors will not be able to use the spacebar properly in the Search Box on that page.
Below is the the code I am using for the spacebar on the game's page.
The Search Box is input type search, so I was wondering if a function could be make for :search, to revert the spacebar to work correctly inside the Search Box.
var hit = document.getElementById("hit");
document.onkeydown = function(e)
{
if (e.keyCode == 32)
{
e.preventDefault();
hit.click();
}
};
thanks
There are many ways you could do this, here's one:
var hit = document.getElementById("hit");
document.onkeydown = function(e) {
if (e.keyCode == 32) {
if (e.currentTarget.type === 'input') { //Or whatever check you want here
// Do things for your searchBox
return; //Prevent rest of the function from running
}
e.preventDefault();
hit.click();
}
};
Inside the above function you must check if the cursor is in your search box, and if it is then skip the rest of the function
Have rewritten your code as below, hope it helps
var hit = document.getElementById("hit");
document.onkeydown = function(e)
{
if (document.activeElement.nodeName != 'TEXTAREA' && document.activeElement.nodeName != 'INPUT') {
if (e.keyCode == 32)
{
e.preventDefault();
hit.click();
}
}
};
Cheers mate!
You can stop the 'keydown' events from the search bar from propagating upwards by calling event.stopPropagation():
document.addEventListener('keydown', function(e) {
console.log('hit!');
e.preventDefault();
});
let search = document.getElementById("search");
search.addEventListener('keydown', function(e) {
console.log("search!");
e.stopPropagation();
});
<form id="search"><input name="query" type="text"><input type="submit" value="search"></form>
I'm trying to validate a character to make sure it's a letter (not a number, symbol, etc.) BEFORE it's allowed to be entered into the form field. How can I do that with JavaScript?
Here is something I tried:
<script type="text/javascript">
function checkTest() {
var letterValue = document.forms[0].test.value;
var letterCheck = /[a-z]/i;
var letterTest = letterValue.test(letterCheck);
}
</script>
<html>
<body>
<form>
<input type="text" name="test" onkeypress="checkTest();"/>
</form>
</body>
</html>
This code will check the string of the value. I've tried using var letterLeng= letterValue.length and then using var letterChar = letterValue.charAt(letterLeng) or even var letterChar = letterValue.charAt(letterLeng - 1) and all to no avail. Any advice would be much appreciated.
Ask the event for the key that was pressed then test it:
function checkTest(event) {
event = event || window.event;
if (!/[A-Za-z]/.test(String.fromCharCode(event.keyCode || event.which))) {
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
}
<input type="text" name="test" onkeypress="checkTest(event);"/>
I like Alex K's answer, but I could not get the 'onkeypress' handler to work so I tried something using Jquery. It doesn't keep the bad letters from appearing briefly, but it does keep them from being entered.
It uses the 'keyup' event, which actually makes checking for the key code much easier in this instance since you want to limit it to [a-zA-Z]
$("#myinput").on("keyup", function (e) {
// Ignore the shift key.
if (e.keyCode === 16) {
return true;
}
if ((e.keyCode < 65 || e.keyCode > 90)) {
var str = $("#myinput").val();
$("#myinput").val(str.slice(0, str.length - 1));
}
});
The working fiddle is here: http://jsfiddle.net/yaa9snce/
What you are looking for is the onkeypress event.
<input type="text" onkeypress="myFunction()">
<script>
function myFunction() {
alert("You pressed a key inside the input field");
}
</script>
Ok..I've been working all day on a demo CRUD app learning some Bootstrap and JS basics...
I've almost got what I want but the last thing is I need it to do is while in the editbox to grab the keycode 13 event (enter) and so send the right class to a function that already works..
it all goes something like this...
$(function() {
...
...
$(document).on("blur", "input#editbox", function(){ saveEditable(this) });
});
function saveEditable(element) {
$('#indicator').show();
var User = new Object();
User.id = $('.current').attr('user_id');
User.field = $('.current').attr('field');
User.newvalue = $(element).val();
var userJson = JSON.stringify(User);
$.post('Controller.php',
{
action: 'update_field_data',
user: userJson
},
function(data, textStatus) {
$('td.current').html($(element).val());
$('.current').removeClass('current');
$('#indicator').hide();
},
"json"
);
}
function makeEditable(element) {
$(element).html('<input id="editbox" size="'+ $(element).text().length +'" type="text" value="'+ $(element).text() +'" onkeypress="return checkForEnter(event)">');
$('#editbox').focus();
$(element).addClass('current');
}
function checkForEnter(e){
if (e.keyCode == 13) {
saveEditable(e);
return false;
}
}
It works pretty good on the blur event firing but just isn't quite there for ENTER
here is the link...just Load the table and see http://markenriquez.tekcities.com/credapp
advTHNAKSance
You are passing event as argument to saveEditable() method from checkForEnter(). Wherein you should pass input field reference instead.
Try this,
function checkForEnter(e){
if (e.keyCode == 13) {
saveEditable(e.target);
return false;
}
}
Hope this helps.
$(window).on("keypress", "input#editbox",function(e){
if(e.keyCode == 13){
do_something();
}
});
PS. Your textarea top-left and bottom-left corners are rounded.
There are lots of solutions on the web for stopping the enter key from submitting a form. Most commonly to use <body onkeypress = ...
But these seem to have the undesired side effect of stopping the enter key working in a multi-line text box. Does anyone know of a way around this, so the enter key will still work in a multi-line text box?
Thanks,
AJ
<script language="Javascript">
document.onkeydown = function() {
if (event.keyCode == 13) {
if (document.activeElement.tagName.toLowerCase () != "textarea") {
event.preventDefault();
return false;
}
}
}
</script>
Something like this?
You can try the following (with jquery):
$(function(){
$('input:not(textarea)').live('keypress', function(e) {
if (e.which == 13) return false;
if (e.which == 13) e.preventDefault();
});
});
Only input fields are targeted, not textareas.
NON JQUERY
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode;
else
key = e.which;
return (key != 13);
}
And add onKeyPress on all text inputs
<input type="text" name="textIn" onKeyPress="return disableEnterKey(event)"/>
Ref : http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx