I am making a small calculator (just for JavaScript learning) and I have two input fields for fraction calculation:
Field: numerator
Field: denominator
And a button "Calculate fraction" which executes the function myFraction(numerator,denominator) when user clicks on it.
Is it possible to do the same without the Button?
I mean JavaScript should recognize that someone is making input and then calculate the fraction automatically.
You can hook into the onkeyup or onkeydown event handlers and call your function:
<input type="text" id="numerator" onkeyup="myFraction()" />
<input type="text" id="denominator" onkeyup="myFraction()" />
You'll need to grab the values of the text boxes inside the myFraction() function and check to see if they're blank before you output the fraction value to the screen though.
function myFraction() {
if(document.getElementById("numerator").value != "" &&
document.getElementById("denominator").value != "") {
...do calculations
}
}
Sure, I think you need onChange() (as the text is being edited) or onBlur() (when the textbox looses focus). See the difference here.
Since you're studying, jQuery can help with some of the nuances - including here.
Javascript is event driven, so yes, you can catch the event after they are typing with keyup or when the user moves off from a textbox control.
You could check the length of a textbox after they leave it, validate what they entered and then run the calculation.
I usually use blur to catch after a user leaves a textbox. I usually use Onchange for select.
Related
Please note: I do not want to use jQuery for this (otherwise I like it)
Problem: I have come to situation where I need to do some javascript function after an user changes an input field (e.g. input type="text"). So I said to myself - I remember an onchange event - BUT onchange event runs AFTER user leaves the field, but I need the function to be called for example every time user types a character to that field. Wowhead shows nice example of what I am trying to achieve this (field with placeholder "Search within results...")
Summary: I am looking for a SIMPLE way of detecting REAL onchange event(not the classic HTML one)and through that call a JS function while not using jQuery?
Use onkeyup instead of onchange then.
Following is a simple way of invoking each type of Key Press on field.
input type="text" onkeypress="myFunction()
Get Example here
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onkeypress
Enjoy..
you can also use onkeyup and onkeydown instead of onkeypress.
Tried onkeypress="myFunction()" or onkeyup="myFunction()"?
There are also events for onfocus and onblur for entering and leaving a textfield :)
You should use "input" event. keyup and keypress don't work if a user modified the value only by a mouse.
When typing into a <input type="text"> field I would like to precheck every entered value before it appears on the screen. E.g. if the user enters any non numeric value, nothing will happen and only if he enters a numeric value the field will change.
Which is the right event to use keydown(), keyup() or is there something better? How do I cancel the current change of the text field without having to remember the old value and manually resetting it?
You could bind to the keypress event and then check the character represented by the which property of the event object. If it isn't a number you can use preventDefault to prevent the default behaviour of writing the character to the element:
$("#someInput").keypress(function(e) {
if(isNaN(String.fromCharCode(e.which))) {
e.preventDefault();
}
});
Here's a working example.
I have two inputs that together form a single semantic unit (think an hours and minutes input together forming a time input). If both inputs lose focus I want to call some Javascript function, but if the user merely jumps between those two, I don't want to trigger anything.
I've tried wrapping these two inputs in a div and adding an onBlur to the div, but it never triggers.
Next I tried adding onBlurs to both inputs and having them check the other's :focus attribute through jQuery, but it seems that when the onBlur triggers the next element hasn't received focus yet.
Any suggestions on how to achieve this?
EDIT: Someone questioned the purpose of this. I'd like to update a few other fields based on the values contained by both these inputs, but ideally I don't want to update the other fields if the user is still in the process of updating the second input (for instance if the user tabs from first to second input).
I made a working example here:
https://jsfiddle.net/bs38V/5/
It uses this:
$('#t1, #t2').blur(function(){
setTimeout(function(){
if(!$('#t1, #t2').is(':focus')){
alert('all good');
}
},10);
});
var focus = 0;
$(inputs).focus(function() { focus++ });
$(inputs).blur(function() {
focus--;
setTimeout(function() {
if (!focus) {
// both lost focus
}
}, 50);
});
An alternative approach is to check the relatedTarget of the blur event. As stated in the MDN documentation this will be the element which is receiving the focus (if there is one). You can handle the blur event and check if the focus has now been put in your other input. I used a data- attribute to identify them, but you could equally well use the id or some other information if it fits your situation better.
My code is from an angular project I've worked on, but the principle should translate to vanilla JS/other frameworks.
<input id="t1" data-customProperty="true" (blur)="onBlur($event)">
<input id="t2" data-customProperty="true" (blur)="onBlur($event)">
onBlur(e: FocusEvent){
const semanticUnitStillHasFocus = (val.relatedTarget as any)?.dataset?.customProperty === "true";
// Do whatever you like with this knowledge
}
What is the purpose of this behavior ?
The blur event triggers when a field looses focus, and only one field can gain focus at a time.
What you could do, in case of validation for instance, is to apply the same function on blur for both the fields and check the values of the fields altogether.
Without a context, it is difficult to help you more.
d.
I have already implemented a version of the code below on my development system.
function validateTextBox(textBoxId) {
var textBox = document.getElementById(textBoxId);
if(document.activeElement.id != textBox.id) {
do validation
}
}
The HTML is similar to:
<input type="text" id="ValidateMe" onChange="validateTextBox('ValidateMe');"/>
The idea is that validation takes place only after the user has completed editing the textbox and that, unlike an onBlur event, validation only fires when the value of the textbox has actually changed.
It seems to work I'm just leery of using it without some review and feedback. I haven't seen any similar code examples. So please give me your thoughts on the implementation and any alternate ideas you may have.
Thanks
This is a fine solution. Do keep in mind that the onchange event will typically only fire when the focus changes (ie. onblur)
If you want to do validation while the user is typing you can use onkeydown/onkeyup/onkeypress but that's quite a ways harder.
Additionally you can use this so you don't have to assign an id to each field and remember to pass it to the validate function:
function validate(input_element) {
alert(input_element.value)
}
<input type="text" name="name" onchange="validate(this);"/>
My site has an input box, which has a onkeydown event that merely alerts the value of the input box.
Unfortunately the value of the input does not include the changes due to the key being pressed.
For example for this input box:
<input onkeydown="alert(this.value)" type="text" value="cow" />
The default value is "cow". When you press the key s in the input, you get an alert("cow") instead of an alert("cows"). How can I make it alert("cows") without using onkeyup? I don't want to use onkeyup because it feels less responsive.
One partial solution is to detect the key pressed and then append it to the input's value, but this doesn't work in all cases such as if you have the text in the input highlighted and then you press a key.
Anyone have a complete solution to this problem?
NOTE: It's over a decade (!!) since I wrote this answer. The input event has become ubiquitous, and should be used instead of this hack.
What does keydown/keyup even mean for tablet and voice input devices?
The event handler only sees the content before the change is applied, because the mousedown and input events give you a chance to block the event before it gets to the field.
You can work around this limitation by giving the browser a chance to update the field's contents before grabbing its value - the simplest way is to use a small timeout before checking the value.
A minimal example is:
<input id="e"
onkeydown="window.setTimeout( function(){ alert(e.value) }, 1)"
type="text" value="cow" />
This sets a 1ms timeout that should happen after the keypress and keydown handlers have let the control change its value. If your monitor is refreshing at 60fps then you've got 16ms of wiggle room before it lags 2 frames.
A more complete example (which doesn't rely on named access on the Window object would look like:
var e = document.getElementById('e');
var out = document.getElementById('out');
e.addEventListener('input', function(event) {
window.setTimeout(function() {
out.value = event.target.value;
}, 1);
});
<input type="text" id="e" value="cow">
<input type="text" id="out" readonly>
When you run the above snippet, try some of the following:
Put the cursor at the start and type
Paste some content in the middle of the text box
Select a bunch of text and type to replace it
Please, try to use oninput event.
Unlike onkeydown, onkeypress events this event updates control's value property.
<input id="txt1" value="cow" oninput="alert(this.value);" />
Note that in newer browsers you'll be able to use the new HTML5 "input" event (https://developer.mozilla.org/en-US/docs/DOM/window.oninput) for this. Most non-IE browsers have supported this event for a long time (see compatibility table in the link); for IE it's version >/9 only unfortunately.
keyup/down events are handled differently in different browsers. The simple solution is to use a library like mootools, which will make them behave the same, deal with propagation and bubbling, and give you a standard "this" in the callback.
To my knowledge you can't do that with a standard input control unless you roll your own.
Jquery is the optimal way of doing this. Please reference the following below:
let fieldText = $('#id');
let fieldVal = fieldText.val();
fieldText.on('keydown', function() {
fieldVal.val();
});