Detect programmatical changes on a html select box - javascript

Is there a way to make a HTML select element call a function each time its selection has been changed programmatically?
Both IE and FF won't fire 'onchange' when the current selection in a select box is modified with javascript. Beside, the js function wich changes the selection is part of framework so I can't change it to trigger an onchange() at then end for example.
Here's an example:
<body>
<p>
<select id="sel1" onchange="myfunction();"><option value="v1">n1</option></select>
<input type="button" onclick="test();" value="Add an option and select it." />
</p>
<script type="text/javascript">
var inc = 1;
var sel = document.getElementById('sel1');
function test() {
inc++;
var o = new Option('n'+inc, inc);
sel.options[sel.options.length] = o;
o.selected = true;
sel.selectedIndex = sel.options.length - 1;
}
function myfunction() {
document.title += '[CHANGED]';
}
</script>
</body>
Is there any way to make test() call myfunction() without changing test() (or adding an event on the button)?
Thanks.

If you can extend/modify the framework to give a hook/callback when they change the select options, it would be better (one way could be to use the dynamic capabilities of js to duck type it in?).
Failing that, there is an inefficient solution - polling. You could set up a setTimeout/setInteval call that polls the desired select option dom element, and fire off your own callback when it detects that something has changed.
as for the answer to your question
Is there any way to make test() call
myfunction() without changing test()
(or adding an event on the button)?
yes, by using jquery AOP http://plugins.jquery.com/project/AOP , it gives an easy-ish solution.
<body>
<p>
<select id="sel1" onchange="myfunction();"><option value="v1">n1</option></select>
<input type="button" onclick="test();" value="Add an option and select it." />
</p>
<script type="text/javascript">
var inc = 1;
var sel = document.getElementById('sel1');
function test() {
inc++;
var o = new Option('n'+inc, inc);
sel.options[sel.options.length] = o;
o.selected = true;
sel.selectedIndex = sel.options.length - 1;
}
function myfunction() {
document.title += '[CHANGED]';
}
//change to aop.after if you want to call afterwards
jQuery.aop.before( {target: window, method: 'test'},
function() {
myfunctino();
}
);
</script>
</body>

Define your own change function that calls the framework function and then calls a
callback function.
e.g.:
function change(callback)
{
frameworkchange();
callback();
}

The answer is .... no.
The DOM only fires the onchange event as a result of user action not code. It does not provide any additional events to hook in this regard.
You will need to customise the framework or drop your requirement.

ahem...
you can access the event 'onpropertychange' it contains a property within the event arguments to identify which property was changed.
It detects both 'selectedIndex' and 'value' changes - simply case test 'propertyName' I'm currently working with the ASP.NET js framework here is some straight copy-paste code for that:
1) define handler:
this._selectionChangedHandler = null;
2) assign handler
this._selectionChangedHandler = Function.createDelegate(this, this._onSelectionChanged);
3) attach handler to event
$addHandler(element, "propertychange", this._selectionChangedHandler);
4) create function
_onSelectionChanged: function(ev) {
if (ev.rawEvent.propertyName == "selectedIndex")
alert('selection changed');
},

With JQuery, you could do something like
$(document).ready(function(){
$('#select-id').change(function(e){
e.preventDefault();
//get the value of the option selected using 'this'
var option_val = $(this).val();
if(option_val == "v1"){
//run your function here
}
return true;
});
});
This would detect the change programmatically and let you respond to each item changed

Related

Enable and disable onclick funtion

I am dynamically creating a table where i am adding onclick function to each column.
for (var x = 0; x < r.length; x++) {
//Setting the columns
if (i === 1) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = r[x];
headerCell.id = x;
headerCell.onclick = function () {
sortTable(this.id, name);
}
row.appendChild(headerCell);
}
}
In a specific situation I want to disable the onclick function. Here is the code and it works.
$('#errorTable TH').prop("onclick", null).off("click");
and in another situation i want to reattach the onclick function. And that doesn't work. I want to enable the original function....
Any ideas ?
The way you created your table and adding/removing events are not easily maintainable. I also have some suggestions:
Review your code and define code click handler separately.
If you use jQuery in your project use it every where, if not, do not use it anywhere.
In your code i is undefined.
Add Remove Event Listener with jQuery
First define your handler function:
var myClickHandler = function(){
// this is your click handler
alert('Yes!!!');
}
Select your element and assign to a variable. <div id="clickable">Click Me!</div> must be in the DOM at the time of below script executed.
var element = $('#clickable');
// assign event listener
element.on('click',myClickHandler);
// remove event listener:
element.off('click',myClickHandler);
note that you must have to inform jQuery which handler should be removed.
See a sample https://codepen.io/softberry/pen/BEpove
An alternative is to build a click handler that checks a "kill switch".
var tableClickable = true;
headerCell.onclick = function () {
if (tableClickable) {
sortTable(this.id, name);
}
}
//In a specific situation I want to disable the onclick function.
something.addEventListener('someEvent', function () {
tableClickable = false;
});
//and in another situation i want to reattach the onclick function.
something.addEventListener('someOtherEvent', function () {
tableClickable = true;
});

bind javascript function to input control on window load

I amm develloping an web form with multiple text box with same css class.
and i want to bind a specific method to all these textboxes who use that class.
belows are my codes
window.onload = function ()
{
var tObj = document.getElementsByClassName('exa');
for (var i = 0; i < tObj.length; i++) {
tObj[i].onblur(convertAmount(event,this));
}
}
the another function 'convertAmount()' is below
function convertAmount(evt, obj) {
if (obj.value != "") {
var num = parseFloat(obj.value);
num = Math.round((num + 0.00001) * 100) / 100;
obj.value = num.toFixed(2);
}
else {
obj.value = "0.00";
}
}
html codes
<div>
<input type="text" id="finalvalue" class="exa"/>
<input type="text" id="grossvalue" class="exa"/>
<div>
when browser load first time only '0.00' values are coming on those text boxes. but when i type some values on those text boxes and press tab its not working! please help what is wrong here
As commented before, you should assign a eventHandler and not pass it as callback.
So you code would be:
tObj[i].onblur = convertAmount.bind(this, event, this);
Also, event is default argument for any eventListener and current object/element is automatically binded to it, so above code can be simplified to
tObj[i].onblur = convertAmount;
This will bind the context and you will get all properties in this.
Sample Fiddle
Note: you should use addEventListener instead. onBlur = will replace all previous events. addEventListener will add another one.
Sample Fiddle
I hope this link helpful to you.
<div>
<input type="text" id="finalvalue" class="exa"/>
<input type="text" id="grossvalue" class="exa"/>
<div>
$(document).ready(function(){
$('.exa').each(function(index,value){
$(this).attr('onblur',convertAmount(event,$(this)))
})
})
function convertAmount(evt, obj) {
if (obj != "") {
$(obj).val('0.00')
}
else {
$(obj).val('0.00')
}
}

How can I disable a button after click

I am using the following script to set my colors:
<script type="text/javascript">
if (localStorage.buttonColor) {
document.getElementsByTagName('html')[0].className = localStorage.buttonColor
}
function getButtonColor(buttonName) {
localStorage.buttonColor = buttonName;
document.getElementsByTagName('html')[0].className = buttonName
}
</script>
Here's my HTML:
<form class="ng-pristine ng-valid">
<button name="darkBlue" onclick="getButtonColor(this.name)">Blue</button>
<button name="black" onclick="getButtonColor(this.name)">Black</button>
</form>
How can I make it so that when a color is chosen that the button to select that color is
disabled so that It cannot be selected again? Then when another button is clicked the other(s) are enabled. Also I need to set the button that's chosen from localstorage to disabled. Sorry I didn't not mention this fully in the question earlier.
function getButtonColor(button) {
button.disabled = "disabled"
localStorage.buttonColor = button.name;
document.getElementsByTagName('html')[0].className = button.name
}
and simply send this:
<button name="darkBlue" onclick="getButtonColor(this)">Blue</button>
<button name="black" onclick="getButtonColor(this)">Black</button>
<disclaimer> inline javascript is evil</disclaimer>
In addition to other answers (just send the button in the handler), you can use this when initially setting the color from localStorage (assuming your 'form' is the first child of 'body'):
if (localStorage.buttonColor) {
document.getElementsByTagName('html')[0].className = localStorage.buttonColor
var buttons = document.body.getElementsByTagName('form')[0].getElementsByTagName('button')
for(var i =0; i < buttons.length; i++)
if(buttons[i].name == localStorage.buttonColor) button.disabled = true
}
Although you might want to consider using jQuery if you often need to find elements in your code, since the getElementsByTagName selections can get verbose.
You can also use :
function getButtonColor(button) {
var elem=documentt.getElementById(button.id);
elem.removeAttribute("onclick");
}
Preferred is to use this and bind it to a variable (often that).
In this you get the html-object who called the function.
http://www.quirksmode.org/js/this.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
function getButtonColor() {
var that = this;
localStorage.buttonColor = that.Name;
document.getElementsByTagName('html')[0].className = that.Name;
that.disabled = "disabled";
}

function in javascript not working when called

I have a javascript code that works by removing the first and the last line of it.
Please take a look at JSFiddle
for people who wants to see it in here, here is my html:
<input id="search" onclick="search()" type="button" value="Search"/>
my javascript :
function search() {
var search = document.getElementById('search');
var int = setInterval(function() {
if (search.value.length == 6)
search.value = 'Searchi';
else if (search.value.length == 7)
search.value = 'Searchin';
else if (search.value.length == 8)
search.value = 'Searching';
else {
search.value= 'Search';
}
//clearInterval( int ); // at some point, clear the setInterval
}, 500);
}
I want the function to work only when I click the button.
You've selected jQuery in jsfiddle.net which by default causes the site to wrap your whole code in a document.ready handler.
The result is that your search function becomes a local function within that wrapper, and not a global variable as required by a DOM0 onclick handler.
Set the jsfiddle options to "no wrap (body)" and "No-Library (pure js)" to turn off that functionality.

I want to trigger an event every single time data changes in an HTML text input field regardless of focus

How do you catch the client-side event when a browser changes an input text field using the browser's autocomplete feature for a plain HTML input field? (This is the small dropdown on input fields that is supplied by the browser, I know that you can disable it with "autocomplete=off" in some browsers per input field.)
I'm already binding to the "change/keyup" event, but these don't handle the case when the user starts typing in a value and uses the Browser's native autocomplete to fill in the rest of the field (and staying in the focus of the field.)
The only foolproof way I know of to always catch ALL changes no matter how they're done is to use a setInterval. This is somewhat CPU intensive, though, so you probably want to try to keep the selector more minimal than this.
setInterval( function() {
$('input').each( function() {
if ($(this).val() != $(this).attr("_value")) {
// Save the new value
$(this).attr("_value", $(this).val());
// TODO - Handle the changed value
}
});
}, 100);
I'm surprised that the 'change' event doesn't fire to be honest...
Anyway, Plutor has the right idea. A more CPU friendly version of his answer:
var value,
elem = $('input[name=email]')[0];
setInterval(function(){
if (elem.value !== value) { /* do something */ }
value = elem.value;
}, 100);
you can call your function in your function for next time after many seconds , try this :
function startTime() {
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h+":"+m+":"+s;
var t = setTimeout(function(){startTime()},500);
}
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
<!DOCTYPE html>
<html>
<head></head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
reference is : http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock

Categories