onChange not firing when input is populated by javascript?

Hello,

I have a date selector that populates an input box. My input box looks like:


<input type="text" name="date_input" id="date_input" onchange="this.form.submit()">
<script language="JavaScript">
	new tcal ({
		'formname': 'make_graph',
		'controlname': 'date_input'
	});

Now, when the input box is populated, the onsubmit doesnt trigger. I have tried adding the following to the end of the javascript file for the date selection, but it has no effect:


var formInput = document.getElementById('date_input');
formInput.onchange();

Attached is the javascript file that I am using, is there something simple I am missing here to get it to trigger?

onchange is not fired when the value of an input is changed. It is only changed when the input’s value is changed and then the input is blurred. What you’ll need to do is capture the keypress event when fired in the given input. Then you’ll test the value of the input against the value before it was keypressed.

I guess I am kind of confused. My onchange works perfectly for a drop down, perhaps an input box is different.

Nobody is manually typing information into this box though, it is getting populated automagically by a calendar pop up. How would I know if this has been done, and then trigger the form being submitted? Im not very good with javascript at all.

That’s because some browsers recognize the deselecting of the <select> element’s child element <option> as a blur on the entire element. You can’t trust this to be consistent. The best way is to use JQuery for this.

if you want to run this on all inputs, you could make a class called inputs and put it on all the inputs, or you can manually select inputs, and selects (whichever is easier for you, if it’s dynamically generated than putting a class isn’t much effort).



var currentInputValue = '';

$('.inputs').focus(function(){
    currentInputValue = $(this).val();
});

$('.inputs').keypress(function(){
    if(currentInputValue != $(this).val())
    {
        alert('Changed!');
        currentInputValue = $(this).val();
    }
});

$('.inputs').blur(function(){
    if(currentInputValue != $(this).val())
    {
        alert('Changed!');
        currentInputValue = $(this).val();
    }
});

This will capture the typing in an input, or pressing of the down arrow on a <select>. It also does its magic on the blur even to capture changes made to a <select> that were with the mouse.

Assuming you can’t, or don’t want to change the code which populates that text field, your next best option is to poll for changes. You would use setInterval() to check the value every half a second or so.