Javascript TextBox input value is not updating - javascript

My requirement is on a keypress I need to get the value of the particular textbox. But the problem is when I press the first letter am getting a blank output. on second keypress am getting the first letter which I have entered in the textbox. Form here on Its getting a one step delay. Is am missing anything.
<script>
document.addEventListener('keypress',function(e){
var keycode = e.keyCode || e.which;
if(document.activeElement.id == 'k_id_234'){
console.log(document.getElementById('k_id_234').value);
}
});
</script>
<input type="text" id="k_id_234">
Text Box : h console : // empty
Text Box : he console : h //only first letter
....
......

Use keyup event instead
document.addEventListener('keyup', function (e) {
var keycode = e.keyCode || e.which;
if (document.activeElement.id == 'k_id_234') {
console.log(document.getElementById('k_id_234').value);
}
});
Demo: Fiddle
jQuery get input value after keypress
Another option is the input event

Related

jQuery to prevent user from inputting if regular expression is not matched by using preventdefault

Every time user enter, value is checked with regular expression, I'm trying to restrict user from entering further into input field if regexp is not matched
Using keyup event, preventdefault never fires and using keypress event, user is unable to input at all because in the begining, value in input field shows as "" (nothing)
var discountRegex = /(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/
$("#" + (idOfElement)).on("keyup",function (e) {
var val=this.value
var k = e.keyCode
if(k==46 ||(k > 48 && k <97)){
console.log(k)
return discountRegex.test(val);
}
});
in the above code idOfElement is the id i get on whichever field i focus.
Please refer sample code. If input key is invalid input will not accept it. Also please find fiddle for same in comment.
<input type="text">
$(document).ready(function(){
$("input").bind('keypress', function(e) {
var str = e.keyCode;
if (/(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/.test(str)) {
alert('Invalid')
e.preventDefault();
} else {
alert('Valid');
}
});
});
You can check if the regex is matched and if not you can remove the last char like the example below
I updated the code with keydown example
Example

If keycode && input are not empty do something

I have barcode input in which I enter barcodes multiple times, every time I add barcode, barcode is added to the list even if I only press enter with empty value.
I want to start function only if user press enter key == 13 and value is not empty.
This is code:
if(key == 13) {}
I tried but without success:
var value = $("#barcode").val();
if(key == 13 && value.length > 0)
{alert("This works!")}...
You need to run your code under either the keyup or keypress event. Assuming you use jQuery to attach the event, you should also use the which property of the provided event object to get the keycode. Try this:
$('#barcode').keypress(function(e) {
if (e.which == 13 && this.value) {
alert("This works!")
}
})
Working example

How make an action run only when the field becomes unselected?

Right now the value of an input text field changes upon the successful match in my code. It looks like this:
if(jsonResponse.id != null) {
document.getElementById('product_id').value = jsonResponse.id;
}
The problem is that if, i.e., I have a product with id=200 and a product with id=2003, then when a user wants to search for 2003, the moment the typed value is 200 - the input field text will change with the corresponding answer for 200, instead of 2003. This is not convenient.
So my goal is to add some additional check (or something like that), that will allow document.getElementById('product_id').value = jsonResponse.id; only after the cursor is not anymore in the input text field (when the field is not selected anymore).
To run a function when a text field loses focus, you can use jQuery's blur event handler:
$('.mytextfield').blur(function(){
var value = $(this).val();
// use value
});
jsbin example
You wait for user to press enter, as soon as user press the enter then process the text.
document.onkeypress = function(e) {
e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode==13) { //ENTER PRESSED
/* your code */
}
};
You can do also like this:
<input type="text" name="name" value="" onblur="yourFunction();"/>
Or by Jquery.

jQuery - get the index of <input> throwing a keypress event

I'm trying to get the index of an input between a set of inputs. Basically, I have a table that contains, on more than one row, many inputs.
Once the user press the "enter" button, while the input is focused, I need to jump to the next input field, as the "tab" key do.
I was following this accepted response, and this is what I've done so far: Fiddle
CODE
$(document).keypress(function(e){
if( e.which == 13 && e.target.nodeName == 'INPUT'){
var inputs = $("#inputsTable input.td_in");
alert(inputs.index(this));
}
});
as you can see, every time you focus an input and then press ENTER, the popup msg says "-1"..
What am I doing wrong? I've been struggling with this piece of code for an hour, and I'm giving up.
I found out that replacing this with e.target also works.
CODE
$(document).keypress(function(e){
if( e.which == 13 && e.target.nodeName == 'INPUT'){
var inputs = $("#inputsTable input.td_in");
alert(inputs.index(e.target));
}
});
That's because this references the document, not your input.
Use .on(), and pass it an input.td_in selector:
$('#inputsTable').on('keypress', 'input.td_in', function (e) {
if( e.which == 13 ) {
var inputs = $("#inputsTable input.td_in");
alert(inputs.index(this));
}
});
P.S. You should probably cache that selector.
$(document).on('keypress', 'input', function (e) {
if( e.which == 13 ){
var inputs = $("#inputsTable input");
var the_index = inputs.index(this);
inputs[the_index+1].focus();
}
});
http://jsfiddle.net/5DwHw/1/

Selecting text on-the-fly from textbox leaves out last character in javascript

I'm trying to get the text from a textbox as a user types, so that I can parse it and display information accordingly as the user enters a command. However, it seems as though the function I'm writing is getting the text from the box before the letter is entered into the text box. How do I prevent the function from grabbing the content from the textbox before the typed character is entered? I considered grabbing the id of the key and altering the inputted string accordingly, but I feel like there should be a better way.
The code:
$('#inputConsoleForm').keydown(function(event){
//Get key code
var code = (event.keyCode ? event.keyCode : event.which);
//Get console text (doesn't behave as expected)
var consoleCommand = document.inputConsoleForm.console.value;
function parseConsoleCommand(consoleCommand) {
/* Returns true if command is valid*/
}
if(code === 13) {
event.preventDefault();
if(!parseConsoleCommand(consoleCommand))
alert("INVALID COMMAND LINE");
else
attemptExecute();//Runs the command
}
if(code === 32 || (code >= 48 && code <= 123) || code === 61 || code === 109 || code === 188 || code === 8) {
if(parseConsoleCommand(consoleCommand)){
$(document.inputConsoleForm.console).css("background-color", "#FFDFDF");
}
else{
$(document.inputConsoleForm.console).css("background-color", "");
}
}
});
You could use the HTML5 input event (falling back to the propertychange event in IE < 9). Here are two answers detailing how to do this:
jQuery keyboard events
Catch only keypresses that change input?
Use "change" for best results I'd say. You could continue to use keydown (or keyup) but you'll have to fetch the key being pressed from the event object and append it to the text string.

Categories