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
Related
I have a type="date" input that onchange fires some JS. My problem is that if you want to clear the date with the "cross button" on the right of the input tag, it will not fire the onchange event, unless you have previously changed the value. It seems really weird to me. My question: can I fire JS when my first action is clicking the "cross button" that delete the date?
I'm using Firefox 58.0.1
Edit: Now if working as expected (sept 2020, Firefox 80.0.1)
function myFunction(IdTag) {
var x = document.getElementById(IdTag).value;
alert('The new value is: '+x);
}
<input type="date" id="MyID" value="2018-02-06" onchange="myFunction('MyID');">
Worked for me.
I created an html file with this content:
<html>
<head></head>
<body>
<input type="date" id="MyID" value="2018-02-06" onchange="myFunction('MyID');">
<script>
function myFunction(IdTag) {
var x = document.getElementById(IdTag).value;
alert('The new value is: '+x);
}
</script>
</body>
</html>
And the event fired and also cleared the date (which was set to MM/DD/YYYY).
Make sure you're not seeing any errors in the Developer Tools.
I had this same issue as well (FF 64.0.1 on Linux) and I solved it by utilising the 'mousedown' event.
Essentially when the mousedown event triggers set up a timer that will manually trigger the onchange on your date input after a certain time, I found 500ms was sufficient for my use case.
I am using jQuery and got it to work, the process should be fairly similar for native JS:
$('input[name="start_date"]').on('mousedown',function() {
var $this = $(this);
setTimeout(function(){ $($this).trigger('change'); }, 500);
});
I had the same problem, and after some research i figured out that there is already a unconfirmed bug Report at Mozilla Bugtracker.
I am using jQuery and my solution was to call focus and blur after binding the even
$('#datefield').on('change', someFunction).focus().blur();
because the bug only appears if someone clicks on the reset button before giving the input the focus. By set and remove the focus to the input, the user does not recognize anything and the bug is bypassed.
So far this code has worked well in Chrome, Firefox, and Safari, however during testing in IE, the onclick event is not firing in any version of IE. We've tested IE7—IE11.
The purpose of this code is to populate data selected from a drop-down into a text input box after clicking the "Update" button.
Here is a snippet:
HTML
<input type="button" value="Update" onclick="javascript:updateText();">
jQuery
<script>
function updateText() {
//** Removes first option of select **//
$("option#ddlOptionsSelect.ng-binding").remove();
//** Populates option selected from dropdown into a text input field **//
document.getElementById("ctl00_cphMainContent_ucDialCustomization_Duc18264_StringTextBox").value =
$('#Dial_18269 #ddlOptions').val();
document.getElementById("ctl00_cphMainContent_ucDialCustomization_Duc18265_StringTextBox").value =
$('#Dial_18459 #ddlOptions').val();
document.getElementById("ctl00_cphMainContent_ucDialCustomization_Duc18266_StringTextBox").value =
$('#Dial_18456 #ddlOptions').val();
document.getElementById("ctl00_cphMainContent_ucDialCustomization_Duc18267_StringTextBox").value =
$('#Dial_18457 #ddlOptions').val();
document.getElementById("ctl00_cphMainContent_ucDialCustomization_Duc18268_StringTextBox").value =
$('#Dial_18460 #ddlOptions').val();
}
</script>
Any suggestions would be helpful as to why this script is not working in Internet Explorer but works in every other browser.
In addition to giving the input an id and attaching and onClick to it using jQuery, you can also simply change the onclick property of you input to onclick="updateText();"
Use JQuery for the event listener:
$("#<id>").on("click", function(){
updateText();
});
You just need to ad an Id to the button.
<input type="button" value="Update" id="<id>">
ex.jsfiddle
I've been working on trying to trigger an onchange listener with java script in Mozilla Firefox. I've found a lot on Stack Overflow posted about this, but nothing seems to be working for my unique case.
I've created this HTML with a onchange listener from an onchange event using this helpful post (JavaScript OnChange Listener position in HTML markup). Here's my code:
<HTML>
<head>
<script type="text/javascript">
window.onload= function () {
if(window.addEventListener) {
document.getElementsByClassName('search-box')[0].addEventListener('change', loadXMLDoc, false);
} else if (window.attachEvent){
document.getElementsByClassName('search-box')[0].attachEvent("onchange", loadXMLDoc);
}
function loadXMLDoc(){
alert('It worked');
}
}
function addTextCallListener() {
var searchBox = document.getElementsByClassName("search-box")[0];
searchBox.value = "Hello";
}
</script>
</head>
<BODY>
<input type="text" class="search-box" placeholder="Player Search">
<br \>
<button type="button" onclick="addTextCallListener()">Click Me!</button>
</BODY>
</HTML>
I also saved it as this jsfiddle (for some reason I had to keep it all together for it to work, I couldn't break it up into js and html).
https://jsfiddle.net/josephfedor42/crogL0zd/1/
If you play with this jsfiddle you can see that entering text and pressing enter will trigger the listener and the pop up with the message “It worked” will appear.
But if the button “Click Me!” is pressed it only changes the value of the text box, and the onchange listener is not called.
I realize I could easily add an onchange event to this button. But I want to to trigger the listener by programatically/ superficially using javascript in my addTextCallListener() function.
I've tried the simple stuff, like calling
searchBox.onchange();
searchBox.focus();
searchBox.click();
And a combination of these to add and remove the focus. But it doesn't seem to work. I've found quite a few posts on triggering an onchange event, but nothing that works in Firefox.
Any help would be appreciated.
Thanks for that link of a possible duplicated question. I had checked out that link before.
But I gave it a try again. I saved the jsfiddle from them both and neither one work.
My implementation of Dorian's answer
https://jsfiddle.net/josephfedor42/zaakd3dj/
My implementation of Alsciende's answer
https://jsfiddle.net/josephfedor42/xhs6L6u2/
emphasize mine
According to the mdn page about the change event,
The change event is fired for <input>, <select>, and <textarea>
elements when a change to the element's value is committed by the
user.
and to whatwg specs :
When the input and change events apply (which is the case for all
input controls other than buttons and those with the type attribute in
the Hidden state), the events are fired to indicate that the user has
interacted with the control.
Therefore, setting the value of an input is not an action "committed by the user" nor a sign that "the user has interacted with the control", since it was made by the code.
So, even if the specifications for this event are kind of unclear, the event should not fire when you change its value by code.
Something like this should work:
function addTextCallListener() {
var searchBox = document.getElementsByClassName("search-box")[0];
searchBox.value = "Hello";
//fire the event
if (document.createEvent) {
searchBox.dispatchEvent('change');
} else {
searchBox.fireEvent("onchange");
}
}
Here is the code I needed to add to my function addTextCallListener:
var evObj = document.createEvent('HTMLEvents');
evObj.initEvent( 'change', true, true );
searchBox.dispatchEvent(evObj);
I updated the jsfiddle. The working code is here https://jsfiddle.net/josephfedor42/crogL0zd/7/
Replace onchange with change in this part:
document.getElementsByClassName('search-box')[0].attachEvent("onchange", loadXMLDoc);
Is there a standard cross-browser HTML5 event which corresponds to IE legacy onselectionchange (so it is fired when the current selection changes)?
EDITED, I'm looking to track Selection object changes.
Never too late :
// IE
myEditableElement.onselectionchange = onSelectionChange;
// work on chrome, untested on firefox
myEditableElement.addEventListener('focus', function (event) {
document.addEventListener('selectionchange', onSelectionChange);
});
myEditableElement.addEventListener('focusout', function (event) {
document.removeEventListener('selectionchange', onSelectionChange);
});
// Event
function onSelectionChange (event) {
// todo
}
use onchange
I recommend using jQuery to avoid these cross browser issues, but that does not mean you should skip testing. see here.
Look at Rangy window.getSelection = rangy.getSelection
it might work...
/*
IE 8 getSelection() missing object and properties simple hack
*/
if (window.getSelection == undefined) { /* IE? */
var wgS = setInterval(function(){ /* wait for Rangy */
if (rangy.initialized) {
window.getSelection = rangy.getSelection; /* do the stuff */
clearTimeout(wgS); /* exit */
}
}, 10);
}
Source : Web
you can find the cursor position on the keyup event handler. eg.
function getCursorPos(evt){
if(window.getSelection){
var sel=document.getSelection();
if(sel.rangeCount==0){return;}
var range = sel.getRangeAt(0);
var p=range.startOffset;
}else{
var sel=document.selection;
if(sel){
var range=sel.createRange();
var p=range.offsetLeft;}
}
document.getElementById('myoutposition').innerHTML=p;
}
if(addEventListener){
document.getElementById('myeditbox').addEventlistener('keyup',getCursorPos,false);
}
else{
document.getElementById('myeditbox').attachEvent('onkeyup',getCursorPos);}
<textarea id="myeditbox" style="width:100%;height:100px;"></textarea><br/>
the current cursor position is <output id="myoutposition">0</output>
The standard is onchange:
<select id="myName" onchange="myMethod(this)">
...
</select>
This can also be used for textboxes etc.
See http://www.w3schools.com/tags/ev_onchange.asp.
You might want to take a look at the onChange attribute.
<input type='text' onChange='alert(this.value)'>
The onchange event occurs when the value of an element has been changed.
For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed.
You can use onchange events, it worked perfectly fine with my multi-select.
<select onchange="myFunction()" multiple>.
Initially, I had problems because I was trying to use the multi-select created using bootstrap classes with the onblur event i.e <select onblur="myFunction()" multiple> event. This didn’t work since my multi-select was created using div (which uses bootstrap classes) as a result I could not focusin or focusout and that caused the onblur not to trigger.
On a plain html select the onblur works just fine. So, you can try it as well.
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... :)