简体   繁体   中英

Using Javascript Loop to detect change in similar radio buttons then execute code

I'm working on a form that creates HTML code based on user input and I'm having some trouble with some javascript functionality. I'd like for parts of the form to be hidden unless they're needed (eg if the user wants to add a rebate to the bottle special they're coding, the otherwise hidden rebate fields are displayed.)

Here is some code that I was previously using to hide or show a div (#rebatebs1) based on whether a particular value was selected on a radio button (name="bottlespecial1rebate"):

    hidebottlespecial1Rebate = function () {
        $('#rebatebs1').hide();
    };

    bottlespecial1RebateSelection = function () {
        hidebottlespecial1Rebate();

        switch ($(this).val()) {
            case 'yes':
                $('#rebatebs1').show();
            break;
            case 'no':
                $('#rebatebs1').hide();
            break;
        }
    };


    $(function() {

        $('input[name=bottlespecial1rebate]:radio').change(bottlespecial1RebateSelection);

        bottlespecial1RebateSelection.apply($('input[name=bottlespecial1rebate]:radio'));
    });

My issue is that I have 12 different radiobutton/div combinations that I'd like to apply this code to without copying/pasting it 12 times and changing the selectors each time (eg #rebatebs2 & #bottlespecial2rebate, #rebatebs3 & #bottlespecial3rebate, etc).

I tried writing a for loop that replaced the number with a variable, but I don't know enough about javascript (I'm a self-taught novice) to make it work, unfortunately. If anyone can point me in the right direction for making it work for 12 different radio button/div combos, I'd really appreciate it.

Change your HTML as, Here You can data-related-div in custom data- * attribute

<input type="radio" name="bottlespecial1rebate" value="yes" 
    data-related-div="rebate1">Yes<br>
<input type="radio" name="bottlespecial1rebate" value="no" 
    data-related-div="rebate1">No   

HTML

You can use Attribute Starts With Selector [name^="value"] to bind events such as

$('input:radio[name^="bottlespecial"]').change(bottlespecial1RebateSelection);

You can store divs to show/hide with HTML can be fetched using .data()

bottlespecial1RebateSelection = function () {
    var relatedDiv = "#" + $(this).data('related-div');
    switch ($(this).val()) {
        case 'yes':
            $(relatedDiv).show();
        break;
        case 'no':
            $(relatedDiv).hide();
        break;
    }
};

Fiddle DEMO

A quick and dirty way would be something like this

var ids = ['list', 'of', 'radio', 'button', 'id'];

for (var i in ids) {
    (function(ids[i]){
        var el = $('#'+id);
        var bottlespecial1RebateSelection = function() {
            el.hide();

            switch ($(this).val()) {
                case 'yes':
                    el.show();
                break;
                case 'no':
                    el.hide();
                break;
            }
        }
        el.change(bottlespecial1RebateSelection);
        bottlespecial1RebateSelection.apply(el);
    })(id)
}

The only special thing is the for-loop, since you are generating functions inside for-loop (which is highly discouraged), you need to use a self-executing function to reserve the value of i . This is often known as infamous loop javascript problem

However, if you are going to work on Javascript long-term, knowing this kind of stuff can be beneficial because in some special cases generating functions within for-loop will save you a lot of time

to detect the change for all of your radio buttons you can first wrap your radio buttons in a div element and give that a unique ID like bottlespecialrebates do:

$(document).on("change","#bottlespecialrebates input:radio", function(){
    bottlespecial1RebateSelection.apply($(this));
});

or just use a kind of the attribute contains selector (use ^= sign):

$(document).on("change","input[name^=bottlespecial]:radio", function(){
    bottlespecial1RebateSelection.apply($(this));
});

the whole point is the way you add the change listener.

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