简体   繁体   中英

Getting event listener to fire

I have a script that I am using in conjunction with a PHP form. I am trying to get a counter field that I put on the form to count up by one second after the employee id field is filled out below is my code.

<script type="text/javascript">

var counter = 0;
var timer;
var employee = document.getElementsByName("employeeID")[0];

var employeeVal = document.getElementsByName("employeeID")[0].value;

employee.addEventListener("onchange", startCount);

function countUP () {
    counter = counter + 1; //increment the counter by 1
    document.getElementsByName("timer_container")[0].value = counter;
 }

 function startCount () {
    timer=setInterval('countUP()', 1000 );
 }

 function readonly() {
     document.getElementsByName("timer_container")[0].readOnly = true;
 }

</script>

I have tried different functions to see if the event listener was firing. I also tried using different events, onclick, onblur and have not had any luck. I've taken the timer function and set it to onload in the body tag directly on the HTML and that works. However I need this to be able to run as soon as someone enters info into the employee field.

First, don't use on in the event name when using .addEventListener . The on prefix is only for inline event binding with HTML event attributes (which is why it worked for you in <body onload=...> ). Inline event HTML attributes shouldn't be used anymore anyway . So, your line should be:

employee.addEventListener("change", startCount);

And use the input event instead of the change event if you want it to fire as data is being entered.

employee.addEventListener("input", startCount);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM