How to clear a textarea value in jQuery? - javascript

I'm trying to validate keycode entry by adding an alert when a user types a key that isn't expected, and then clearing the text area. The alert functions correctly but the text area isn't clearing.
I've checked the documentation here, but I can't see an area with my .val() line. I've also tried this: $("#noteNumberInput").attr('value', "");
Scenario: I type 1-9 in the text box and get no alert (works fine), if I type a letter a-z for example, the alert pops up but the letter remains in the text box.
EDIT:
Something I've noticed is that it does clear the textarea after the first key. If I type the letter 'a' and then 'b', the 'a' is removed and replaced with a 'b'.
HTML:
<textarea id="noteNumberInput" placeholder="Note number"></textarea>
JS:
var noteNumberInput = document.getElementById("noteNumberInput");
//VALIDATE NOTE NUMBER TEXTAREA
function validate(key) {
var keycode = (key.which) ? key.which : key.keyCode;
//comparing pressed keycodes
if (keycode === 8 || (keycode >= 48 && keycode <= 57)) {
return true;
}
if (keycode < 48 || keycode > 57) {
alert("Please only enter the note number e.g. 1, 2..14 etc.");
$("#noteNumberInput").val("");
return false;
}
}
noteNumberInput.addEventListener("keydown", validate);

When you do $("#noteNumberInput").val('');, it removes all the content of the textarea, so if that's not what is happening, the problem is probably somewhere else.

Change noteNumberInput.addEventListener("keydown", validate); to use keyup

Using $("#noteNumberInput").val() will clear the textarea
EDIT
The problem is the keydown handler. In this case the function will be triggered followed by the display of alert & then the text area will be populated. But on using keyup the function will be triggered on release of the key.So by that time the textarea will be populated with value.
Change the keydown to keyup
var noteNumberInput = document.getElementById("noteNumberInput");
noteNumberInput.addEventListener("keyup", validate);
DEMO

Your only asking for the validate() function to actually execute when you've pressed the next key.

I think that´s not the best idea to trigger key events, because cut and paste and drag and drop can also change the input element.
try this:
Element.addEventListener('input', function(){
this.value=this.value.replace(/[^0-9,.]/g, '');
});
this must be adapted to textarea...

Related

How to set listeners to "backspace press" event in Javascript or Jquery?

I have a button that is enabled or disabled if, respectively, there is or is not text inside an input, as shown in the code snippet below:
var input = document.getElementById('myInput');
var btn = document.getElementById('myButton');
$(input).on('keyup', function(){
if((input.value != null) && (input.value != ''))
$(btn).removeClass('btnDisabled');
else
$(btn).addClass('btnDisabled');
});
Using keyup event it is working good in my aplication on an smarthphone with Android 6.0.1. But for some reason, on an tablet with Android 4.4.2 if backspace key are pressed till the begin of input, erasing all the text value, the button is still enabled.
I researched this problem but I'm still not sure if the WebView version interferes with this. I think so.
I used other code snippets to see if the event is triggered by the "backspace" button, as shown below:
$(input).on('keydown', function(event){ //I tried keyup, keydown and keypress
var key = event.keyCode || event.charCode;
console.log("keydown " + key, "length " + input.value.length);
//if(key == 8 && input.value.length == 1) $(btn).addClass('btnDisabled');
});
With this test I saw that the backspace does not trigger the event and the variable key is always equal to 0.
I need to disable the button when input is empty. Where am I going wrong?
Right now, I thank those who help! :D
There is another event that you can use: input
https://developer.mozilla.org/en-US/docs/Web/Events/input
The DOM input event is fired synchronously when the value of an <input>, <select>, or <textarea> element is changed.
In this case, change
$(input).on('keydown',
to
$(input).on('input',
See also: https://caniuse.com/#search=input

OnKeyDown or KeyPress, detect the location of the inserted character

I don't know if this is possible (it looks like it's not), but I'm trying to find a way to detect, inside the onKeyDown or onKeyPress event of an HTML input tag, what the resulting value will be.
It's important that I use these events. I can't just use onKeyUp, because by then the input will have already changed. I want to prevent it from happening in the first place. I've also tried appending the pressed key character to the end of the string, but that doesn't account for cases where you typed a character in the beginning of the string in the input field.
Any ideas? I've looked for a while and it doesn't seem possible but I figured I'd ask.
Here I have 2 versions, one with jQuery and other with JavaScript alone.
$("#inputJQuery").on("keydown", function(ev){
console.log("jQuery value:", $(this).val()); // this is the value before the key is added
console.log("jQuery selectionStart:", this.selectionStart); // the position where the character will be inserted
console.log("jQuery selectionEnd:", this.selectionEnd); // if has a selection this value will be different than the previous
})
document.querySelector("#inputVanilla").onkeydown = function(ev){
console.log("VANILLA value:", this.value); // this is the value before the key is added
console.log("VANILLA selectionStart:", this.selectionStart); // the position where the character will be inserted
console.log("VANILLA selectionEnd:", this.selectionEnd); // if has a selection this value will be different than the previous
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input id="inputJQuery" type="text"/>
<input id="inputVanilla" type="text"/>
Simply check for the length of the value on keydown. This also works for deleting characters.
You can also check against this in a conditional that returns false to prevent the user from typing in more than a certain number of characters. Note that you'll probably want to check this against the backspace and delete keys (keyCodes 8 and 46 respectively) so that you're able to delete keys once the maximum length is reached.
var input = document.getElementById('input');
input.onkeydown = function(e) {
console.log(input.value.length);
if (input.value.length == 10) {
if (e.keyCode === 8 || e.keyCode === 46) {
return true;
} else {
return false;
}
}
}
<input id="input">
Hope this helps! :)

Color change only after key press

So I have a page when you enter a HEX and it'll change to that background. The issue is, you need to press space first for some reason. My question is how can I have it so that then on the initial load, you can just enter it without pressing space? Here's my code for the background change with input
$('.hex').keyup(function(){
var a = $(this).val();
$('#example').text(a);
console.log(a);
$('body').css('background', '#'+a);
});
Here's a demo. Enter a hex in the first box. Nothing will happen, Then press space and enter another hex.
You need to place the onkeyup event handler registering code outside the onkeydown event handler.
Here is the code in onkeydown event handler:
$(document).keydown(function(e) {
if (e.keyCode == '32') {
//...
//you placed the onkeyup event handler registering code here
//which is wrong
}
}
//you should place the code here
$('.hex').keyup(function(){
var a = $(this).val();
$('#example').text(a);
console.log(a);
$('body').css('background', '#'+a);
});
Updated demo.
It's because everithing is in if statement where it checks for if (e.keyCode == '32') and keyCode==32 is space.

Trigger Keypress event of a input field on keypress of another input field?

I have two input fields i want to trigger keypress of one input field on keypress of another input field.
What i have tried is
$('#example').keypress(function(event) {
var press = jQuery.Event("keypress");
var code = event.keyCode || event.which;
press.which = code ;
$('#search').trigger(press);
});
both example and search are input fields. Why i am doing so i because when i enter text in simple field it has to enter text in another field which filters search results.
Try this :
JavaScript
$('#example').on('keypress keyup keydown',function(event) {
// create the event
var press = jQuery.Event(event.type);
var code = event.keyCode || event.which;
press.which = code ;
// trigger
$('#search').val(this.value);
$('#search').trigger(event.type, {'event': press});
});
// Omit - Check if search box reacts
$('#search').on('keypress keyup keydown',function(event) {
// sample
console.log(event.type);
});
Demo here : http://jsbin.com/pebac/1/edit
Note that even if you successfully manage to trigger a keypress event this doesn't act as a real one, meaning that the char won't be appended to the input.
Guess it's like $.click()
$('#search').keypress();
If all you want to do is to copy the content of one field to the other, I'd say it's better to do $('#search').val($(this).val()); instead of triggering the keypress event on #search.

Pass keydown event to another textbox

I'm trying to pass an keydown event from one textbox to another. What I mean with this is that if you, for example, press the 'a' key, some code should simulate that key as being pressed in the second textbox.
I do not want to just copy the value of the first textbox into the second - it should be on a per-key basis so to say. Suppose the first textbox contains abc and the second textbox is empty, when you then press the 'd' key in textbox 1, textbox 2 should only contain d.
What I already tried is (http://jsfiddle.net/E5qyr/1/):
$('#t1').keydown(function(e) {
$('#t2').keydown(e);
});
But this does not work (I guess I'm thinking too simple). I know I could append the character pressed by looking at e.keyCode, but also 'backspace' etc. has to be working.
Does anybody have an idea to pass a keydown event from one textbox to another?
Textarea elements don't have listeners automatically installed to them, so triggering a 'keydown' event for the #t2 will not show a response. What you want is to just add the text you get from the #t1 keydown event (of which you are listening) and append it to your #t2.
UPDATED with support for backspace. Other codes found here.
Example:
$('#t1').keydown(function(e) {
if (e.which == 8) { //Backspace
this.text(this.val().substr(0, this.val().length - 1));
} else {
$('#t2').append($('#t1').val());
this.empty();
}
});
Why not replace textbox value onkeydown? It seems it would be more simples to just do txt1.text = txt2.text instead of appending the existing strings in txt1.
Something like this?
$('#t1').keydown(function(e) {
var char = (e.keyCode == 8) ? '' : String.fromCharCode(e.keyCode + (e.shiftKey ? 0 : 32));
$('#t2').val(char);
});

Categories

Resources