Tisal
Tisal

Reputation: 155

Jquery manipulating number of elements with given pattern of id

Code below hides a section if radio button is unchecked.

if ($('#Items_0__Suffix:checked').val() === 'No') {
        $('#section0').hide();
    }

Now if we have multiple items, what is the succinct way to write code rather than code like below:

if ($('#Items_0__Suffix:checked').val() === 'No') {
        $('#section0').hide();
    }
if ($('#Items_1__Suffix:checked').val() === 'No') {
            $('#section0').hide();
        }

Upvotes: 1

Views: 42

Answers (3)

Adam Gerard
Adam Gerard

Reputation: 746

Create a function and pass in the context. Reuse the remaining code. Example:

Var doWork = function(context) {
       If ($(context).val() == 'No') {
            $('#section0').hide();
       }
 }

This way you can call the same function and code for reuse without having to duplicate it each time.

Upvotes: 0

DinoMyte
DinoMyte

Reputation: 8868

Assuming that the sequence of the checkbox id starts with zero and has the corresponding element whose id also starts with zero, you can use jquery starts with selector and use jquery index() to figure out the element to show/hide.

$("[id^=Items_]").on("click",function()
{        
   var index = $(this).index();
   !$(this).is(":checked") ? 
   $('#section' + index).hide() : $('#section' + index).show();
});

Example : https://jsfiddle.net/97bo2vyb/2/

Upvotes: 1

SirUncleCid
SirUncleCid

Reputation: 187

Perhaps a for loop?

for (var i = 0; i <= amountOfButtons; i++) {
    if ($('#Items_' + i + '__Suffix:checked').val() === 'No') {
        $('#section0').hide();
    }
}

Or even using Regex in your selectors could do the trick.

Upvotes: 0

Related Questions