jQuery fire event if input is changed through Javascript - javascript

I need to fire an event if the input text has changed through Javascript using .val(), from jQuery API (https://api.jquery.com/change/): Note: Changing the value of an input element using JavaScript, using .val() for example, won't fire the event.
Have tried this How can I trigger an onchange event manually? but doesn't seem to work...
This is my code:
<input type="text" id="datePrint" maxlength="10" size="6" disabled>
<img src="scripts/calendar/calendar.png" id="datePick" border="0" align="absmiddle" alt="Pick Date" width="40px" height="40px">
JS: need to activate calendar events
Calendar.setup({inputField:'datePrint',ifFormat:'%d/%m/%Y',button:'datePick',align:'T1',singleClick:true});
And this is the calendar JS:
http://www.mediafire.com/view/yfrls2nx4m6ls52/calendarJs.txt

You can always trigger the change event while changing the input value.
$("input#id").trigger('change');

There are two ways. The simple answer is remember that every-time you use .val() to also call .change().
However, this begs the question on whether the DOM is the best place to keep state information. A more complex but flexible solution is to create a model/view object to store state and let it manage the events and updates.
However, upon further inspection on the comments the actual problem your attempting to address is not how to trigger change events but how to tell when an input has changed when another third party lib has pragmatically changed it.
The first step is to investigate the library in question and see if they provide a change event you can attach to. If not (after considering a different better behaved library), you are probably stuck with a polling solution.
function InputChangePoller(selector) {
this.el = $(selector);
this._lastKnownValue = this.el.val();
}
InputChangePoller.prototype.start = function() {
this._timmer = setImmediate($.proxy(this, 'checkValue'), 10);
return this;
};
InputChangePoller.prototype.stop = function() {
clearImmediate(this._timmer);
return this;
};
InputChangePoller.prototype.checkValue = function() {
var value = this.el.val();
if (value !== this._lastKnownValue) {
this._lastKnownValue = value;
this.el.trigger('change', value);
}
};

Related

what is the best jsript event handler to use when data is change through other script for select? [duplicate]

The logic in the change() event handler is not being run when the value is set by val(), but it does run when user selects a value with their mouse. Why is this?
<select id="single">
<option>Single</option>
<option>Single2</option>
</select>
<script>
$(function() {
$(":input#single").change(function() {
/* Logic here does not execute when val() is used */
});
});
$("#single").val("Single2");
</script>
Because the change event requires an actual browser event initiated by the user instead of via javascript code.
Do this instead:
$("#single").val("Single2").trigger('change');
or
$("#single").val("Single2").change();
I believe you can manually trigger the change event with trigger():
$("#single").val("Single2").trigger('change');
Though why it doesn't fire automatically, I have no idea.
Adding this piece of code after the val() seems to work:
$(":input#single").trigger('change');
As far as I can read in API's. The event is only fired when the user clicks on an option.
http://api.jquery.com/change/
For select boxes, checkboxes, and
radio buttons, the event is fired
immediately when the user makes a
selection with the mouse, but for the
other element types the event is
deferred until the element loses
focus.
To make it easier, add a custom function and call it whenever you want to change the value and also trigger a change:
$.fn.valAndTrigger = function (element) {
return $(this).val(element).trigger('change');
}
and
$("#sample").valAndTrigger("NewValue");
Or you can override the val() function to always call the change when val() is called:
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
this.trigger("change");
return originalVal.call(this, value);
};
})(jQuery);
Sample at http://jsfiddle.net/r60bfkub/
In case you don't want to mix up with default change event you can provide your custom event
$('input.test').on('value_changed', function(e){
console.log('value changed to '+$(this).val());
});
to trigger the event on value set, you can do
$('input.test').val('I am a new value').trigger('value_changed');
If you've just added the select option to a form and you wish to trigger the change event, I've found a setTimeout is required otherwise jQuery doesn't pick up the newly added select box:
window.setTimeout(function() { jQuery('.languagedisplay').change();}, 1);
I ran into the same issue while using CMB2 with Wordpress and wanted to hook into the change event of a file upload metabox.
So in case you're not able to modify the code that invokes the change (in this case the CMB2 script), use the code below.
The trigger is being invoked AFTER the value is set, otherwise your change eventHandler will work, but the value will be the previous one, not the one being set.
Here's the code i use:
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
if (arguments.length >= 1) {
// setter invoked, do processing
return originalVal.call(this, value).trigger('change');
}
//getter invoked do processing
return originalVal.call(this);
};
})(jQuery);
$(":input#single").trigger('change');
This worked for my script. I have 3 combos & bind with chainSelect event, I need to pass 3 values by url & default select all drop down. I used this
$('#machineMake').val('<?php echo $_GET['headMake']; ?>').trigger('change');
And the first event worked.
To change the value
$("#single").val("Single2");
Also to trigger a change event
$("#single").val("Single2").change();
this logic is instrumental when multiple select options are on a page.
one changes and other select options have to change but do not trigger a change event.

Why is my onchange function called twice when using .focus()?

TLDR
Check this example in chrome.
Type someting and press tab. see one new box appear
type something and press enter. see two new boxes appear, where one is expected.
Intro
I noticed that when using enter rather then tab to change fields, my onchange function on an input field was firing twice. This page was rather large, and still in development (read: numerous other bugs), so I've made a minimal example that shows this behaviour, and in this case it even does it on 'tab'. This is only a problem in Chrome as far as I can tell.
What it should do
I want to make a new input after something is entered into the input-field. This field should get focus.
Example:
javascript - needing jquery
function myOnChange(context,curNum){
alert('onchange start');
nextNum = curNum+1;
$(context.parentNode).append('<input type="text" onchange="return myOnChange(this,'+nextNum+')" id="prefix_'+nextNum+'" >');
$('#prefix_'+nextNum).focus();
return false;
}
HTML-part
<div>
<input type="text" onchange="return myOnChange(this,1);" id="prefix_1">
</div>
the complete code is on pastebin. you need to add your path to jquery in the script
A working example is here on jFiddle
The onchange gets called twice: The myOnChange function is called, makes the new input, calls the focus(), the myOnChange gets called again, makes a new input, the 'inner' myOnChange exits and then the 'outer' myOnchange exits.
I'm assuming this is because the focus change fires the onchange()?. I know there is some difference in behaviour between browsers in this.
I would like to stop the .focus() (which seems to be the problem) to NOT call the onchange(), so myOnChange() doesn't get called twice. Anybody know how?
There's a way easier and more reasonable solution. As you expect onchange fire when the input value changes, you can simply explicitly check, if it was actually changed.
function onChangeHandler(e){
if(this.value==this.oldvalue)return; //not changed really
this.oldvalue=this.value;
// .... your stuff
}
A quick fix (untested) should be to defer the call to focus() via
setTimeout(function() { ... }, 0);
until after the event handler has terminated.
However, it is possible to make it work without such a hack; jQuery-free example code:
<head>
<style>
input { display: block; }
</style>
<body>
<div></div>
<script>
var div = document.getElementsByTagName('div')[0];
var field = document.createElement('input');
field.type = 'text';
field.onchange = function() {
// only add a new field on change of last field
if(this.num === div.getElementsByTagName('input').length)
div.appendChild(createField(this.num + 1));
this.nextSibling.focus();
};
function createField(num) {
var clone = field.cloneNode(false);
clone.num = num;
clone.onchange = field.onchange;
return clone;
}
div.appendChild(createField(1));
</script>
I can confirm myOnChange gets called twice on Chrome. But the context argument is the initial input field on both calls.
If you remove the alert call it only fires once. If you are using the alert for testing only then try using console instead (although you need to remove it for testing in IE).
EDIT: It seems that the change event fires twice on the enter key. The following adds a condition to check for the existence of the new field.
function myOnChange(context, curNum) {
nextNum = curNum+1;
if ($('#prefix_'+nextNum).length) return false;// added to avoid duplication
$(context.parentNode).append('<input type="text" onchange="return myOnChange(this,'+nextNum+')" id="prefix_'+nextNum+'" >');
$('#prefix_'+nextNum)[0].focus();
return false;
}
Update:
The $('#prefix_'+nextNum).focus(); does not get called because focus is a method of the dom object, not jQuery. Fixed it with $('#prefix_'+nextNum)[0].focus();.
The problem is indeed that because of the focus(), the onchange is called again. I don't know if this is a good sollution, but this adding this to the function is a quick sollution:
context.onchange = "";
(The onchange is called again, but is now empty. This is also good because this function should never be called twice. There will be some interface changes in the final product that help with problems that would arise from this (mistakes and all), but in the end this is something I probably would have done anyway).
sollution here: http://jsfiddle.net/k4WKH/2/
As #johnhunter says, the focus does not work in the example, but it does in my complete code. I haven't looked into what's going on there, but that seems to be a separate problem.
maybe this some help to anybody, for any reason, in chrome when you attach an event onchage to a input text, when you press the enterkey, the function in the event, do it twice, i solve this problem chaged the event for onkeypress and evaluate the codes, if i have an enter then do the function, cause i only wait for an enterkey user's, that not works for tab key.
input_txt.onkeypress=function(evt){
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
if(charCode === 13) evaluate( n_rows );
};
Try this example:
var curNum = 1;
function myOnChange( context )
{
curNum++;
$('<input type="text" onchange="return myOnChange( this )" id="prefix_'+ curNum +'" >').insertAfter( context );
$('#prefix_'+ curNum ).focus();
return false;
}
jsFiddle.

How to detect a textbox's content has changed

I want to detect whenever a textbox's content has changed. I can use the keyup method, but that will also detect keystrokes which do not generate letters, like the arrow keys. I thought of two methods of doing this using the keyup event:
Check explictly if the ascii code of the pressed key is a letter\backspace\delete
Use closures to remember what was the text in the textbox before the key stroke and check whether this has changed.
Both look kinda cumbersome.
Start observing 'input' event instead of 'change'.
jQuery('#some_text_box').on('input', function() {
// do your stuff
});
...which is nice and clean, but may be extended further to:
jQuery('#some_text_box').on('input propertychange paste', function() {
// do your stuff
});
Use the onchange event in HTML/standard JavaScript.
In jQuery that is the change() event. For example:
$('element').change(function() { // do something } );
EDIT
After reading some comments, what about:
$(function() {
var content = $('#myContent').val();
$('#myContent').keyup(function() {
if ($('#myContent').val() != content) {
content = $('#myContent').val();
alert('Content has been changed');
}
});
});
The 'change' event doesn't work correctly, but the 'input' is perfect.
$('#your_textbox').bind('input', function() {
/* This will be fired every time, when textbox's value changes. */
} );
How about this:
< jQuery 1.7
$("#input").bind("propertychange change keyup paste input", function(){
// do stuff;
});
> jQuery 1.7
$("#input").on("propertychange change keyup paste input", function(){
// do stuff;
});
This works in IE8/IE9, FF, Chrome
Use closures to remember what was the text in the checkbox before the key stroke and check whether this has changed.
Yep. You don't have to use closures necessarily, but you will need to remember the old value and compare it to the new.
However! This still won't catch every change, because there a ways of editing textbox content that do not involve any keypress. For example selecting a range of text then right-click-cut. Or dragging it. Or dropping text from another app into the textbox. Or changing a word via the browser's spell-check. Or...
So if you must detect every change, you have to poll for it. You could window.setInterval to check the field against its previous value every (say) second. You could also wire onkeyup to the same function so that changes that are caused by keypresses are reflected quicker.
Cumbersome? Yes. But it's that or just do it the normal HTML onchange way and don't try to instant-update.
$(document).on('input','#mytxtBox',function () {
console.log($('#mytxtBox').val());
});
You can use 'input' event to detect the content change in the textbox. Don't use 'live' to bind the event as it is deprecated in Jquery-1.7, So make use of 'on'.
I assume that you are looking to do something interactive when the textbox changes (i.e. retrieve some data via ajax). I was looking for this same functionality. I know using a global isn't the most robust or elegant solution, but that is what I went with. Here is an example:
var searchValue = $('#Search').val();
$(function () {
setTimeout(checkSearchChanged, 0.1);
});
function checkSearchChanged() {
var currentValue = $('#Search').val();
if ((currentValue) && currentValue != searchValue && currentValue != '') {
searchValue = $('#Search').val();
$('#submit').click();
}
else {
setTimeout(checkSearchChanged, 0.1);
}
}
One key thing to note here is that I am using setTimeout and not setInterval since I don't want to send multiple requests at the same time. This ensures that the timer "stops" when the form is submitted and "starts" when the request is complete. I do this by calling checkSearchChanged when my ajax call completes. Obviously you could expand this to check for minimum length, etc.
In my case, I am using ASP.Net MVC so you can see how to tie this in with MVC Ajax as well in the following post:
http://geekswithblogs.net/DougLampe/archive/2010/12/21/simple-interactive-search-with-jquery-and-asp.net-mvc.aspx
I would recommend taking a look at jQuery UI autocomplete widget. They handled most of the cases there since their code base is more mature than most ones out there.
Below is a link to a demo page so you can verify it works. http://jqueryui.com/demos/autocomplete/#default
You will get the most benefit from reading the source and seeing how they solved it. You can find it here: https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.autocomplete.js.
Basically they do it all, they bind to input, keydown, keyup, keypress, focus and blur. Then they have special handling for all sorts of keys like page up, page down, up arrow key and down arrow key. A timer is used before getting the contents of the textbox. When a user types a key that does not correspond to a command (up key, down key and so on) there is a timer that explorers the content after about 300 milliseconds. It looks like this in the code:
// switch statement in the
switch( event.keyCode ) {
//...
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
// when menu is open and has focus
if ( this.menu.active ) {
// #6055 - Opera still allows the keypress to occur
// which causes forms to submit
suppressKeyPress = true;
event.preventDefault();
this.menu.select( event );
}
break;
default:
suppressKeyPressRepeat = true;
// search timeout should be triggered before the input value is changed
this._searchTimeout( event );
break;
}
// ...
// ...
_searchTimeout: function( event ) {
clearTimeout( this.searching );
this.searching = this._delay(function() { // * essentially a warpper for a setTimeout call *
// only search if the value has changed
if ( this.term !== this._value() ) { // * _value is a wrapper to get the value *
this.selectedItem = null;
this.search( null, event );
}
}, this.options.delay );
},
The reason to use a timer is so that the UI gets a chance to be updated. When Javascript is running the UI cannot be updated, therefore the call to the delay function. This works well for other situations such as keeping focus on the textbox (used by that code).
So you can either use the widget or copy the code into your own widget if you are not using jQuery UI (or in my case developing a custom widget).
do you consider using change event ?
$("#myTextBox").change(function() { alert("content changed"); });
I'd like to ask why you are trying to detect when the content of the textbox changed in real time?
An alternative would be to set a timer (via setIntval?) and compare last saved value to the current one and then reset a timer. This would guarantee catching ANY change, whether caused by keys, mouse, some other input device you didn't consider, or even JavaScript changing the value (another possiblity nobody mentioned) from a different part of the app.
Use the textchange event via customized jQuery shim for cross-browser input compatibility. http://benalpert.com/2013/06/18/a-near-perfect-oninput-shim-for-ie-8-and-9.html (most recently forked github: https://github.com/pandell/jquery-splendid-textchange/blob/master/jquery.splendid.textchange.js)
This handles all input tags including <textarea>content</textarea>, which does not always work with change keyup etc. (!) Only jQuery on("input propertychange") handles <textarea> tags consistently, and the above is a shim for all browsers that don't understand input event.
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/pandell/jquery-splendid-textchange/master/jquery.splendid.textchange.js"></script>
<meta charset=utf-8 />
<title>splendid textchange test</title>
<script> // this is all you have to do. using splendid.textchange.js
$('textarea').on("textchange",function(){
yourFunctionHere($(this).val()); });
</script>
</head>
<body>
<textarea style="height:3em;width:90%"></textarea>
</body>
</html>
JS Bin test
This also handles paste, delete, and doesn't duplicate effort on keyup.
If not using a shim, use jQuery on("input propertychange") events.
// works with most recent browsers (use this if not using src="...splendid.textchange.js")
$('textarea').on("input propertychange",function(){
yourFunctionHere($(this).val());
});
There's a complete working example here.
<html>
<title>jQuery Summing</title>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script>
$(document).ready(function() {
$('.calc').on('input', function() {
var t1 = document.getElementById('txt1');
var t2 = document.getElementById('txt2');
var tot=0;
if (parseInt(t1.value))
tot += parseInt(t1.value);
if (parseInt(t2.value))
tot += parseInt(t2.value);
document.getElementById('txt3').value = tot;
});
});
</script>
</head>
<body>
<input type='text' class='calc' id='txt1'>
<input type='text' class='calc' id='txt2'>
<input type='text' id='txt3' readonly>
</body>
</html>
Something like this should work, mainly because focus and focusout would end up with two separate values. I'm using data here because it stores values in the element but doesn't touch the DOM. It is also an easy way to store the value connected to its element. You could just as easily use a higher-scoped variable.
var changed = false;
$('textbox').on('focus', function(e) {
$(this).data('current-val', $(this).text();
});
$('textbox').on('focusout', function(e) {
if ($(this).data('current-val') != $(this).text())
changed = true;
}
console.log('Changed Result', changed);
}
This Code detects whenever a textbox's content has changed by the user and modified by Javascript code.
var $myText = jQuery("#textbox");
$myText.data("value", $myText.val());
setInterval(function() {
var data = $myText.data("value"),
val = $myText.val();
if (data !== val) {
console.log("changed");
$myText.data("value", val);
}
}, 100);
document.getElementById('txtrate' + rowCount).onchange = function () {
// your logic
};
This one works fine but triggers the event on click too which is not good. my system went into loop.
while
$('#txtrate'+rowCount).bind('input', function() {
//your logic
} );
works perfectly in my scenario. it only works when value is changed.
instead of $ sign one can use document.getElementById too

Detect all changes to a <input type="text"> (immediately) using JQuery

There are many ways the value of a <input type="text"> can change, including:
keypresses
copy/paste
modified with JavaScript
auto-completed by browser or a toolbar
I want my JavaScript function to be called (with the current input value) any time it changes. And I want it to be called right away, not just when the input loses focus.
I'm looking for the cleanest and most robust way to do this across all browsers (using jQuery preferably).
This jQuery code uses .bind() to catch immediate changes to any element, and should work across all browsers:
$('.myElements').each(function() {
var elem = $(this);
// Save current value of element
elem.data('oldVal', elem.val());
// Look for changes in the value
elem.bind("propertychange change click keyup input paste", function(event){
// If value has changed...
if (elem.data('oldVal') != elem.val()) {
// Updated stored value
elem.data('oldVal', elem.val());
// Do action
....
}
});
});
However, note that .bind() was deprecated in jQuery version 3.0. Anyone using jQuery version 1.7 or newer should use .on() instead.
A real-time solution for jQuery >= 1.7 is on
$("#input-id").on("change keyup paste", function(){
dosomething();
})
if you also want to detect "click" event, just:
$("#input-id").on("change keyup paste click", function(){
dosomething();
})
if you're using jQuery <= 1.6, just use bind or live instead of on.
Unfortunately, I think setInterval wins the prize:
<input type=text id=input_id />
<script>
setInterval(function() { ObserveInputValue($('#input_id').val()); }, 100);
</script>
It's the cleanest solution, at only 1 line of code. It's also the most robust, since you don't have to worry about all the different events/ways an input can get a value.
The downsides of using 'setInterval' don't seem to apply in this case:
The 100ms latency? For many applications, 100ms is fast enough.
Added load on the browser? In general, adding lots of heavy-weight setIntervals on your page is bad. But in this particular case, the added page load is undetectable.
It doesn't scale to many inputs? Most pages don't have more than a handful of inputs, which you can sniff all in the same setInterval.
Binding to the input event seems to work fine in most sane browsers. IE9 supports it too, but the implementation is buggy (the event is not fired when deleting characters).
With jQuery version 1.7+ the on method is useful to bind to the event like this:
$(".inputElement").on("input", null, null, callbackFunction);
Unfortunately there is no event or set of events that matches your criteria. Keypresses and copy/paste can both be handled with the keyup event. Changes through JS are trickier. If you have control over the code that sets the textbox, your best bet is to modify it to either call your function directly or trigger a user event on the textbox:
// Compare the textbox's current and last value. Report a change to the console.
function watchTextbox() {
var txtInput = $('#txtInput');
var lastValue = txtInput.data('lastValue');
var currentValue = txtInput.val();
if (lastValue != currentValue) {
console.log('Value changed from ' + lastValue + ' to ' + currentValue);
txtInput.data('lastValue', currentValue);
}
}
// Record the initial value of the textbox.
$('#txtInput').data('lastValue', $('#txtInput').val());
// Bind to the keypress and user-defined set event.
$('#txtInput').bind('keypress set', null, watchTextbox);
// Example of JS code triggering the user event
$('#btnSetText').click(function (ev) {
$('#txtInput').val('abc def').trigger('set');
});
If you don't have control over that code, you could use setInterval() to 'watch' the textbox for changes:
// Check the textbox every 100 milliseconds. This seems to be pretty responsive.
setInterval(watchTextbox, 100);
This sort of active monitoring won't catch updates 'immediately', but it seems to be fast enough that there is no perceptible lag. As DrLouie pointed out in comments, this solution probably doesn't scale well if you need to watch lots of inputs. You can always adjust the 2nd parameter to setInterval() to check more or less frequently.
Here is a solution that doesn't make use of jQuery (Its really quite obsolete and not necessary these days)
Using the event "input" you can look for any kind of change:
Deleting, Backspacing, Pasting, Typing, anything that will change the inputs value.
The input event is directly related to the text input. ANY time the text is changed in ANY fashion, input is dispatched.
document.querySelector("#testInput").addEventListener("input", test);
function test(e) {
var a = document.getElementById('output');
a.innerText += "Detected an Update!\n";
}
<input id="testInput">
<br>
<a id="output"></a>
Here is a slightly different solution if you didn't fancy any of the other answers:
var field_selectors = ["#a", "#b"];
setInterval(function() {
$.each(field_selectors, function() {
var input = $(this);
var old = input.attr("data-old-value");
var current = input.val();
if (old !== current) {
if (typeof old != 'undefined') {
... your code ...
}
input.attr("data-old-value", current);
}
}
}, 500);
Consider that you cannot rely on click and keyup to capture context menu paste.
Add this code somewhere, this will do the trick.
var originalVal = $.fn.val;
$.fn.val = function(){
var result =originalVal.apply(this,arguments);
if(arguments.length>0)
$(this).change(); // OR with custom event $(this).trigger('value-changed');
return result;
};
Found this solution at val() doesn't trigger change() in jQuery
I have created a sample. May it will work for you.
var typingTimer;
var doneTypingInterval = 10;
var finaldoneTypingInterval = 500;
var oldData = $("p.content").html();
$('#tyingBox').keydown(function () {
clearTimeout(typingTimer);
if ($('#tyingBox').val) {
typingTimer = setTimeout(function () {
$("p.content").html('Typing...');
}, doneTypingInterval);
}
});
$('#tyingBox').keyup(function () {
clearTimeout(typingTimer);
typingTimer = setTimeout(function () {
$("p.content").html(oldData);
}, finaldoneTypingInterval);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea id="tyingBox" tabindex="1" placeholder="Enter Message"></textarea>
<p class="content">Text will be replace here and after Stop typing it will get back</p>
http://jsfiddle.net/utbh575s/
We actually don't need to setup loops for detecting javaScript changes.
We already setting up many event listeners to the element we want to detect. just triggering any un harmful event will make the job.
$("input[name='test-element']").on("propertychange change click keyup input paste blur", function(){
console.log("yeh thats worked!");
});
$("input[name='test-element']").val("test").trigger("blur");
and ofc this is only available if you have the full control on javascript changes on your project.
Although this question was posted 10 years ago, I believe that it still needs some improvements. So here is my solution.
$(document).on('propertychange change click keyup input paste', 'selector', function (e) {
// Do something here
});
The only problem with this solution is, it won't trigger if the value changes from javascript like $('selector').val('some value'). You can fire any event to your selector when you change the value from javascript.
$(selector).val('some value');
// fire event
$(selector).trigger('change');
Or in a single line
$(selector).val('some value').trigger('change');
Well, best way is to cover those three bases you listed by yourself. A simple :onblur, :onkeyup, etc won't work for what you want, so just combine them.
KeyUp should cover the first two, and if Javascript is modifying the input box, well I sure hope it's your own javascript, so just add a callback in the function that modifies it.
Here's a working example that I'm using to implement an autocomplete variation the populates a jqueryui selector (list), but I don't want it to function exactly like the jqueryui autocomplete which does a drop-down menu.
$("#tagFilter").on("change keyup paste", function() {
var filterText = $("#tagFilter").val();
$("#tags").empty();
$.getJSON("http://localhost/cgi-bin/tags.php?term=" + filterText,
function(data) {
var i;
for (i = 0; i < data.length; i++) {
var tag = data[i].value;
$("#tags").append("<li class=\"tag\">" + tag + "</li>");
}
});
});
Can't you just use <span contenteditable="true" spellcheck="false"> element in place of <input type="text">?
<span> (with contenteditable="true" spellcheck="false" as attributes) distincts by <input> mainly because:
It's not styled like an <input>.
It doesn't have a value property, but the text is rendered as innerText and makes part of its inner body.
It's multiline whereas <input> isn't although you set the attribute multiline="true".
To accomplish the appearance you can, of course, style it in CSS, whereas writing the value as innerText you can get for it an event:
Here's a fiddle.
Unfortunately there's something that doesn't actually work in IE and Edge, which I'm unable to find.
you can simply identify all changers in the form, like this
//when form change, show aleart
$("#FormId").change(function () {
aleart('Done some change on form');
});
You can bind the 'input' event to <input type="text">. This will trigger every time the input changes such as copy, paste, keypress, and so on.
$("#input-id").on("input", function(){
// Your action
})

Javascript event that fires without user interaction?

A textbox on my form may change depending on what's selected in various drop down lists.
Is there a way to call a javascript function when the textbox value changes?
Tried onchange event but this only seems to work if a user manually changes the textbox value.
Cheers,
Breandán
No, javascript-triggered changes to form elements don't trigger events. If they did, this would cause all sorts of recursive infinite loops.
The simple solution is to call your onchange function manually whenever you change the value of the textbox, however you could also use some kind of wrapper function. As a very basic example:
function updateTextField(new_text) {
text_field.value = new_text;
text_field.onchange();
}
When setting the content of the text box from your JS code, call out to another function passing in the text to set, you can then call it from where ever you need and do your logic then.
Try to disconnect the logic responsible for changing the control's value from the onchange event's execution path using a setTimeout.
<html>
<head>
<script type="text/javascript">
function setValue(target) {
alert("changed - value: " + target.value);
setTimeout("reallySetValue('" + target.id + "');", 1);
}
function reallySetValue(id) {
var control = document.getElementById(id);
control.value += control.value;
}
</script>
</head>
<body>
<form>
<div>
Enter "a" here:
<input type="text" id="test" onchange="setValue(this)">
<br/>
<br/>
<input type="text">
</div>
</form>
</body>
</html>
It's illustrated here
Changing a Textbox Value in its OnChange Event
In web browsers, programmatic changes on a control won't trigger events on that control. You must instruct the code that changes the textbox value to trigger the onchange event. This is how you can do it in plain javascript:
var textbox = document.getElementById("boxId");
textbox.value = "Abc";
textbox.onchange();
Of course, using a library like jQuery makes it easier and more robust:
$("#boxId").val("Abc").change();
You can use the excellent event.simulate.js to do this. This script does depend on the Prototype.js library, though.
If you'd want to this without relying on an external library, take a look at the fireEvent and createEvent functions. A simple demonstration of how you could implement this:
function triggerEvent(element, eventName)
{
if (document.createEvent)
{
var evt = document.createEvent('HTMLEvents');
evt.initEvent(eventName, true, true);
return element.dispatchEvent(evt);
}
if (element.fireEvent)
return element.fireEvent('on' + eventName);
}
triggerEvent(document.getElementById('myTextbox', 'change'));
Using event.simululate.js, you would do it like this:
Event.simulate('myTextbox', 'change');
A similiar question was asked here: Trigger an event with Prototype.
EDIT: although it is possible to use document.getElementById('myTextbox').change(), I would not recommend doing it, as it makes your code less flexible. When attaching onChange events to the textbox, these would not trigger when manually calling the change() event. Using the above method, events will propagate, just as if the event was a user-triggered one.
Assuming the frontend is in html:
You could install a timout callback and query the contents of the textbox in intervals of, say, 100msecs and compare it to some previous value you store in a variable.
Keywords: window.setTimout(), window.setInterval()
I'd recommend to look over YUI's Custom events for Example:
YUI Custom Event Example Link
All you need is to attach this script with Events manipulations
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
and then you are able to use Custom Events (everywhere in HTML)
fnSubscriberChange - inside this Func you could do whatever you want. You could put your textbox change value logic here and depend on the Changed Select box value - call desired func.
Logic that depends on Event listening is clear and easy to modify;
YUI library supports all browsers so you shouldnt mind about browsers features.
Text box and select boxes:
<input type='text' id='id_text_fld' value=''/>
<select id='id_sel_one'>
<option value="test1">Test1
<option value="test2">Test2
</select>
<select id='id_sel_two'>
<option value="test3">Test3
<option value="test4">Test4
</select>
Script for events:
<script>
(function() {
//create a new custom event, to be fired
var onChangeValue = new YAHOO.util.CustomEvent("onChangeValue");
// Attach change event listener for Select boxes by their IDs
YAHOO.util.Event.on( ['id_sel_one', 'id_sel_two'], 'change', fnCallback, this);
// Function to call when Change event on Select occures
fnCallback = function(e) {
alert("This elem:" + this.id+ " changed value to:" + this.value);
// Fire our Custom event
onChangeValue.fire({dom_el: this}); // passing select box element [this] to function
}
// Listen for Custom event and call our Func
onChangeValue.subscribe(fnSubscriberChange); // Lets listen for ChangeValue event and call our Func
fnSubscriberChange = function(type, args) {
alert("Event type:" + type + " dom el id:" + args[0].dom_el.id );
var dom_el = args[0].dom_el; // Select Box that produces Change
};
})();
</script>

Categories