简体   繁体   中英

jQuery if radio button is selected then proceed to next element

I'm very new to JavaScript and jQuery. I know my code is not the prettiest, but I'm trying to start somewhere.

I have a series of questions that are shown one at a time, and want to create some sort of validation to prevent the user from going to the next question if a radio button on the first button hasn't been selected.

HTML (I have four of these .questionContainers

<div class="questionContainer">

<div class="question">
     How much storage do you need?
</div>

 <div class="answers">
     <ul>
         <li>
             <label>
                 <input type="radio" id="storage">1GB or less
             </label>
         </li>

         <li>
             <label>
                 <input type="radio" id="storage">More than 1GB
             </label>
         </li>  
     </ul>
 </div>

 <div class="btnContainer">
     <div class="next">
         <a class="btnNext">Next</a>
     </div>
 </div>
</div>

JavaScript

(function(){

    var Questions = {

        container : $('.questionContainer'),

        init : function() {

            this.start();

            if($('input[type=radio]:checked').length > 0){
                this.container.find('a.btnNext').on('click', this.next);
            }

        },

        start : function() {

            this.container.not(':first').addClass('hide');
        },

        next : function() {

            var container = $('.questionContainer');

            $(this).closest(container).hide(function(){
                $(this).closest(container).next().show();       
            });
        }
    };
    Questions.init();
})();

The specific line that isn't working:

if($('input[type=radio]:checked').length > 0) {

   this.container.find('a.btnNext').on('click', this.next);
}

The Problem

When I add the if statement and click a radio button followed by next, it does not go to the next question. I am not receiving any errors in the console.

This binds to the click event only if something is checked at the time that the start function is called (not what you want - it will never be true unless you pre-select a radio button for the user without their action):

        if($('input[type=radio]:checked').length > 0){
            this.container.find('a.btnNext').on('click', this.next);
        }

Try replacing it with this instead:

this.container.find('a.btnNext').on('click', function () {
        if($('input[type=radio]:checked').length > 0){
            this.next();
        }
});

This way you always bind to the click event, but the function that is bound only allows next to be called if something is checked at the time that the function is called (ie when the next button is clicked).

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