Javascript textbox call event when value changes - javascript

I have a textbox, and whenever the value of the box changes, I want to check and see if 20 digits have been entered.
I thought that I would use the onChange event, but this seems to be interpreted as the onBlur event on IE.
So then I thought I would use onKeyDown, but the problem comes in if the user wants to paste a value into the field, then the function never gets called.
There are no other form boxes so I can't rely on onBlur or expect that they will change focus ever.
How do I do this?
I just want to evaluate the value of the textbox every time the value of the textbox changes.
<input type="text" onKeyDown="myfunction()">

An effective way is to use a combination of onkeydown and onpaste, which will work in IE, Firefox, Chrome and Safari. Opera is the odd one out here because it doesn't support onpaste so you may have to fall back to onchange for Opera or use the DOMAttrModified mutation event, see example below.
Internet Explorer also supports onpropertychange, which will fire every time a property changes on an element -- including value. I have read that DOMAttrModified is supported by Opera and Safari (not sure about Firefox), so you could use that in combination with IE's onpropertychange (untested):
if ("implementation" in document &&
document.implementation.hasFeature('MutationEvents','2.0'))
myInput.addEventListener("DOMAttrModified", valueChanged, false);
else if ("onpropertychange" in myInput)
myInput.onpropertychange = valueChanged;
function valueChanged (evt)
{
var attr;
evt = evt || window.event;
attr = evt.attrName || evt.propertyName;
if (attr == "value")
validate();
}

use onKeryPress event
<input type="text" onKeyDown="CountText(this,200)" onpaste="return false;">
function CountText(field, maxlimit)
{
if (field.value.length < maxlimit) // if too long...trim it!
{
return true;
}
else
return false;
}
check my full article on : http://www.codeproject.com/KB/validation/MyTextBox.aspx

<script>
function multy(val)
{
alert(val.value+"--"+val.id);
}
</script>
</head>
<body>
<input id="txtdemo" type="text" onchange="multy(this);"></br>
<input id="txtdemo" type="text" onchange="multy(this);">
</input>
</body>
Thanks... :)

Related

ASP.NET/Webform Textbox does not fire the autopostback when onkeyup event defines "setTimeout" (IE9)

I've a strange situation on IE 9. It just works in Chrome and Firefox. I will post only the relevant code.
It's a legacy application (VS2008). The "corp framework" defines field masks at runtime, it uses the onkeyup event, with javascript like this:
Javascript:
function mascara(o, f) {
v_obj = o
v_fun = f
setTimeout(function() {
v_obj.value = v_fun(v_obj.value)
}, 1)
}
ASP.NET HTML:
<asp:TextBox runat="server" ID="TextBox5" AutoPostBack="true" OnTextChanged="TextChanged" />
The mask and the postback event works in all browsers except IE9. When I remove the setTimeout in the javascript mask function, the postback works, but i lost the mask behavior.
I figure out that AutoPostBack=true will render the onchange event with setTimeout. The mask uses another time the setTimeout function, when I remove the setTimeout in the mask, the postback works at IE 9.
Rendered HTML:
<input name="TextBox5" type="text" onchange="javascript:setTimeout('__doPostBack(\'MPTextBox5\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="MPTextBox5" onkeyup="mascara(this, mnum);">
I can't figure out what is the problem at IE9 and the solution.
MS will not fix this bug:
https://connect.microsoft.com/IE/feedback/details/761843/wont-fire-change-event-if-value-of-input-is-changed-using-keyup
Workaround found at: http://bugs.jquery.com/ticket/10818
// Set value for IE without clearing the "changed" flag
this.innerText = val;
// Set value for everyone else
if ( this.value != val ) {
this.value = val;
}

OnChange not firing in IE

I wish to fire a Onchange event for all the changes of Form elements within a DIV
Here's the snippet
<html>
<body>
<div id="container">
<input type="checkbox"/>
<input type="checkbox"/>
<input type="text"/>
<input type="text"/>
</div>
<script>
di = document.getElementById("container");
di.onchange = function(a){
alert("On Change Called");
}
di.onclick = function(a){
alert("On Click Called");
}
</script>
</body>
</html>
The event is fired, when a focus is lost from any of the form elements to a new element of the form, when some content is updated (eg: the input box is updated)
The above code works fine for all browsers' but not for IE, any way to do this is IE
Actually, IE, especially IE7/8 doesn't support onchange event very well . I do recommend you use onclick event.
onchange event does not bubble in IE according to MSDN.
Avoid using .focus() or .select() before .change() function of jquery for IE, then it works fine, im using it in my site.
Thanks
I had the same problem in Edge and fixed it using an EventListener.
My code looked like this:
HTML:
<input type="text" id="my_id" name="my_name" placeholder="my_placeholder" onchange="my_function(this.value.trim())" autofocus>
Then I changed it to:
HTML:
<input type="text" id="my_id" name="my_name" placeholder="my_placeholder" autofocus>
JS:
document.getElementById("my_id").addEventListener("change", function() {
my_function(this.value.trim())
});
Mostly all web developer must have faced this issue..
yeh the older version of IE sometimes not firing the onChange event and replacing it with onClick works.
But this is not expected with latest IE 11. what I found in my case was the function name being called on onChange event was clashing somewhere. I just changed it to some other name which should sound like unique in the whole context, then it worked.
Conclusion: IE 11 getting confused when finds some similar names
within the system matching with the onchange target function (even
the file names I guess), while the other browsers are intelligent
enough.
I created this code to trigger the onchange event not triggered by Interenet Explorer.
Used with an asp.net textbox
<!-- LOCAL SCRIPT -->
<script type="text/javascript">
$(document).ready(function () {
// CTRL - fix explorer bug for OnChange not triggered. Converted to OnBlur + test
if (navigator.appName == 'Microsoft Internet Explorer')
{
var tempControl = $("#<%= textboxNAME.ClientID %>");
var tempATTRIBUTE = "data-lastvalue";
// GET - save current value inside attribute
tempControl.attr(tempATTRIBUTE, tempControl.val());
// BIND - onblur event
$("#<%= textboxNAME.ClientID %>").blur(function () {
var tempPrevValue = tempControl.attr(tempATTRIBUTE);
// CTRL - is there a difference of value (onchange)
if (tempControl.val() != tempPrevValue) {
// SET - trigger change js binded to textbox
$(this).change();
}
});
}
});
Actually Onchange does not work very well in IE. Here is what I did while using Javascript. You can replicate it accordingly.
Add ondrop event in HTML to call the function being called now, instead of onchange.
Add the following code in your js file
document.getElementById('--your selector--').ondragover = handle;
function handle(evt)
{
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy'
}
The ondragover will be made false by above code, and then ondrop will fire on all browsers and call the required function

Is there a cross-browser solution for monitoring when the document.activeElement changes?

I'm really looking for something that works with all current popular browsers (IE9, Chrome, Firefox, Safari) and all the way back to IE8.
Although, I've been looking for a way to set focus on a Flash move object after it has lost focus, I've found that all historical ways of doing this fail. I assume it is yet another security issue.
So, I'm now looking for how to monitor change events of some sort for the document.activeElement (though "change" doesn't really occur).
While #James's answer above is correct. I've added more details to make it a completely working solution along with the use of focus event too.
<html>
<body>
<input type="text" id="Text1" name ="Text1" value=""/>
<input type="text" id="Text2" name ="Text2" value=""/>
<SELECT><OPTION>ASDASD</OPTION><OPTION>A232</OPTION></SELECT>
<INPUT TYPE="CHECKBOX" id="Check1"/>
<INPUT type="TEXT" id="text3"/>
<input type="radio"/>
<div id="console"> </div>
<textarea id="textarea1"> </textarea>
<script>
var lastActiveElement = document.activeElement;
function detectBlur() {
// Do logic related to blur using document.activeElement;
// You can do change detection too using lastActiveElement as a history
}
function isSameActiveElement() {
var currentActiveElement = document.activeElement;
if(lastActiveElement != currentActiveElement) {
lastActiveElement = currentActiveElement;
return false;
}
return true;
}
function detectFocus() {
// Add logic to detect focus and to see if it has changed or not from the lastActiveElement.
}
function attachEvents() {
window.addEventListener ? window.addEventListener('focus', detectFocus, true) : window.attachEvent('onfocusout', detectFocus);
window.addEventListener ? window.addEventListener('blur', detectBlur, true) : window.attachEvent('onblur', detectBlur);
}
attachEvents();
</script>
</body>
</html>
It seems that you can use a combination of capturing focus/blur and focusin/focusout (IE) events. Something like this perhaps:
window.addEventListener ?
window.addEventListener('blur', blurHappened, true)
: window.attachEvent('onfocusout', blurHappened);
function blurHappened() {
console.log('document.activeElement changed');
}
onfocusout will catch bubbled "blurs" while regular blur on addEventListener will capture "blurs".
You may need to add additional checks in blurHappened. I'm not sure as I haven't tested.
You can capture a focus change on the document using the focusin event listener.
document.addEventListener('focusin', () => {
console.log('focus changed');
});
div {
display: flex;
flex-direction: column;
}
<div>
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
</div>
In my experience, the best source of information on cross-browser issues is Quirksmode. Here's a link to the "obvious" (but not useable) option -- focus and blur events.
http://www.quirksmode.org/dom/events/blurfocus.html
Oddly (and surprisingly) it's Webkit-based browsers that are the fly in the ointment here.
Another option would be to use an interval timer to check whether the activeElement has changed either as your sole option OR as backup for focus/blur. (You could also listen for key presses, mouse clicks, and touches to check if activeElement changes.) If you cover these options, your intervalTimer will hardly ever need to clean up.

Do not allow Paste any non alphanumeric characters

I don’t want user to allow pasting of any non Alphanumeric characters on a text box.
How do I restrict this in Javascript?
Thanks!!
Using jQuery, this is one way to do it:
HTML:
​<form name='theform' id='theform' action=''>
<textarea id='nonumbers' cols='60' rows='10'> </textarea>
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
JavaScript:
$().ready(function(){
$("textarea#nonumbers").keyup(removeextra).blur(removeextra);
});
function removeextra() {
var initVal = $(this).val();
outputVal = initVal.replace(/[^0-9a-zA-Z]/g,"");
if (initVal != outputVal) {
$(this).val(outputVal);
}
};
Try it out here.
EDIT: As remarked in the comments, the original (using the .keyup() event) would have left open the possibility of pasting via the mouse context menu, so I've added a .blur() event. .change() would have been possible too, but there are reports of bugginess. Another option is using .focusout(). Time to experiment...
You can use the onblur event of text box.
function remove()
{
var otxt=document.getElementById('txt1');
var val=otxt.value;
for(i=0;i<val.length;i++)
{
var code=val.charCodeAt(i);
if(!(code>=65 && code<=91) && !(code >=97 && code<=121) && !(code>=48 && code<=57))
{ otxt.value=""; return ; }
}
}
<input type="text" id="txt1" onblur="remove();" />
It will remove all value of text box when you input non alphanumeric value.
Why has no one suggested using the OnPaste event? That is fully supported in IE, Safari and Chrome.
Docs for using OnPaste in IE
Docs for using OnPaste in Webkit
In JQuery, that would look like this:
$(input).bind("paste", function(e){ RemoveNonAlphaNumeric(); })
That covers 75% of the browser market.
If you use JQuery, OnPaste is automatically normalized in Firefox so that it works there too. If you can't use JQuery, there is an OnInput event that works.
The working solution is to use a fast setTimeout value to allow the input's value property to be filled.
Basically like this:
$("input").bind("paste", function(e){RemoveAlphaChars(this, e);});
function RemoveAlphaChars(txt, e)
{
setTimeout(function()
{
var initVal = $(txt).val();
outputVal = initVal.replace(/[^0-9]/g,"");
if (initVal != outputVal)
$(txt).val(outputVal);
},1);
}
I have tested this in IE, Chrome and Firefox and it works well. The timeout is so fast, you can't even see the characters that are being removed.
I'm not sure how you can prevent pasting, but you can filter the contents either on the submit or on the change event.
It's better to validate form - check this great jQuery's plugin - http://docs.jquery.com/Plugins/Validation/ and you can use the "number" rule : http://docs.jquery.com/Plugins/Validation/Methods/number. Really simple and easy to tune thing!
Assuming:
<textarea id="t1"/>
You could modify the onchange event handler for the textarea to strip out anything not alphanumeric:
document.getElementById('t1').onchange = function () {
this.value = this.value.replace(/\W/,'');
}

Textarea onchange detection

How do I detect change event on textarea using javascript?
I'm trying to detect how many characters left is available as you type.
I tried using the onchange event, but that seems to only kick in when focus is out.
The best way to do this, cross-browser: use a combination of the input and onpropertychange events, like so:
var area = container.querySelector('textarea');
if (area.addEventListener) {
area.addEventListener('input', function() {
// event handling code for sane browsers
}, false);
} else if (area.attachEvent) {
area.attachEvent('onpropertychange', function() {
// IE-specific event handling code
});
}
The input event takes care of IE9+, FF, Chrome, Opera and Safari, and onpropertychange takes care of IE8 (it also works with IE6 and 7, but there are some bugs).
The advantage of using input and onpropertychange is that they don't fire unnecessarily (like when pressing the Ctrl or Shift keys); so if you wish to run a relatively expensive operation when the textarea contents change, this is the way to go.
Now IE, as always, does a half-assed job of supporting this: neither input nor onpropertychange fires in IE when characters are deleted from the textarea. So if you need to handle deletion of characters in IE, use keypress (as opposed to using keyup / keydown, because they fire only once even if the user presses and holds a key down).
Source: http://www.alistapart.com/articles/expanding-text-areas-made-elegant/
EDIT: It seems even the above solution is not perfect, as rightly pointed out in the comments: the presence of the addEventListener property on the textarea does not imply you're working with a sane browser; similarly the presence of the attachEvent property does not imply IE. If you want your code to be really air-tight, you should consider changing that. See Tim Down's comment for pointers.
You will need to use onkeyup and onchange for this. The onchange will prevent context-menu pasting, and the onkeyup will fire for every keystroke.
See my answer on How to impose maxlength on textArea for a code sample.
For Google-Chrome, oninput will be sufficient (Tested on Windows 7 with Version 22.0.1229.94 m).
For IE 9, oninput will catch everything except cut via contextmenu and backspace.
For IE 8, onpropertychange is required to catch pasting in addition to oninput.
For IE 9 + 8, onkeyup is required to catch backspace.
For IE 9 + 8, onmousemove is the only way I found to catch cutting via contextmenu
Not tested on Firefox.
var isIE = /*#cc_on!#*/false; // Note: This line breaks closure compiler...
function SuperDuperFunction() {
// DoSomething
}
function SuperDuperFunctionBecauseMicrosoftMakesIEsuckIntentionally() {
if(isIE) // For Chrome, oninput works as expected
SuperDuperFunction();
}
<textarea id="taSource"
class="taSplitted"
rows="4"
cols="50"
oninput="SuperDuperFunction();"
onpropertychange="SuperDuperFunctionBecauseMicrosoftMakesIEsuckIntentionally();"
onmousemove="SuperDuperFunctionBecauseMicrosoftMakesIEsuckIntentionally();"
onkeyup="SuperDuperFunctionBecauseMicrosoftMakesIEsuckIntentionally();">
Test
</textarea>
I know this isn't exactly your question but I thought this might be useful.
For certain applications it is nice to have the change function fire not every single time a key is pressed. This can be achieved with something like this:
var text = document.createElement('textarea');
text.rows = 10;
text.cols = 40;
document.body.appendChild(text);
text.onkeyup = function(){
var callcount = 0;
var action = function(){
alert('changed');
}
var delayAction = function(action, time){
var expectcallcount = callcount;
var delay = function(){
if(callcount == expectcallcount){
action();
}
}
setTimeout(delay, time);
}
return function(eventtrigger){
++callcount;
delayAction(action, 1200);
}
}();
This works by testing if a more recent event has fired within a certain delay period. Good luck!
I know this question was specific to JavaScript, however, there seems to be no good, clean way to ALWAYS detect when a textarea changes in all current browsers. I've learned jquery has taken care of it for us. It even handles contextual menu changes to text areas. The same syntax is used regardless of input type.
$('div.lawyerList').on('change','textarea',function(){
// Change occurred so count chars...
});
or
$('textarea').on('change',function(){
// Change occurred so count chars...
});
You can listen to event on change of textarea and do the changes as per you want. Here is one example.
const textArea = document.getElementById('my_text_area');
textArea.addEventListener('input', () => {
var textLn = textArea.value.length;
if(textLn >= 100) {
textArea.style.fontSize = '10pt';
}
})
<html>
<textarea id='my_text_area' rows="4" cols="50" style="font-size:40pt">
This text will change font after 100.
</textarea>
</html>
Keyup should suffice if paired with HTML5 input validation/pattern attribute. So, create a pattern (regex) to validate the input and act upon the .checkValidity() status. Something like below could work. In your case you would want a regex to match length. My solution is in use / demo-able online here.
<input type="text" pattern="[a-zA-Z]+" id="my-input">
var myInput = document.getElementById = "my-input";
myInput.addEventListener("keyup", function(){
if(!this.checkValidity() || !this.value){
submitButton.disabled = true;
} else {
submitButton.disabled = false;
}
});
Code I have used for IE 11 without jquery and just for a single textarea:
Javascript:
// Impede que o comentário tenha mais de num_max caracteres
var internalChange= 0; // important, prevent reenter
function limit_char(max)
{
if (internalChange == 1)
{
internalChange= 0;
return;
}
internalChange= 1;
// <form> and <textarea> are the ID's of your form and textarea objects
<form>.<textarea>.value= <form>.<textarea>.value.substring(0,max);
}
and html:
<TEXTAREA onpropertychange='limit_char(5)' ...
Try this one. It's simple, and since it's 2016 I am sure it will work on most browsers.
<textarea id="text" cols="50" rows="5" onkeyup="check()" maxlength="15"></textarea>
<div><span id="spn"></span> characters left</div>
function check(){
var string = document.getElementById("url").value
var left = 15 - string.length;
document.getElementById("spn").innerHTML = left;
}
The best thing that you can do is to set a function to be called on a given amount of time and this function to check the contents of your textarea.
self.setInterval('checkTextAreaValue()', 50);

Categories