简体   繁体   中英

Event listener only triggers correctly after second click

I have an event listener that listens for clicks on a group of radio buttons, then passes the checked value to a function.

I then output the checked value to the web console whenever a radio button is selected, but this only works if the radio button is clicked twice after page load.

 var t1q1El = document.getElementById("t1q1"); function question_1() { $(function(){ $("#t1q1").one('click',function(){ var t1q1UserInput = $("input[name=t1q1]:checked").val(); questionsData['question_1']['input'] = t1q1UserInput; assessPoints('question_1', t1q1UserInput); }); }); } t1q1El.addEventListener("click", question_1); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <fieldset id="t1q1"> <label>Strongly Agree <input type="radio" value="strongly-agree" name="t1q1"> </label> <label>Agree <input type="radio" value="agree" name="t1q1"> </label> <label>No Stance <input type="radio" value="no-stance" name="t1q1"> </label> <label>Disagree <input type="radio" value="disagree" name="t1q1"> </label> </fieldset> </form> 

On the second click, the value is passed to the web console immediately after clicking. All consecutive clicks function as expected. Why doesn't the first click trigger anything?

I'm still learning JS so please excuse/correct any bad practices..

Here is what happening:

1) t1q1El.addEventListener("click", question_1); You assign a function to t1q1El . Basically you are saying do question_1 when t1q1El is clicked.

2) Click 1. We do question_1 which is assigning a click event to t1qE1 . Now t1qE1 has 2 events.

3) Click 2. Doing question_1 (which is assigning another click event on itself) and executing that click.

Solution is simple to just assign a click event:

 $(function(){
        $("#t1q1").one('click',function(){
            var t1q1UserInput = $("input[name=t1q1]:checked").val();
            questionsData['question_1']['input'] = t1q1UserInput;
            assessPoints('question_1', t1q1UserInput);
        });
});

BTW one() will execute only once, if you need to keep the event after first executions use on()

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