user3869231
user3869231

Reputation: 342

Javascript loop through array inside an event

I am trying to DRY up this code, specifically instead of manually typing out the elems options in the if/else statement I want to loop through (or increment the numbers). I've tried using all kinds of loops but cant get it to work inside the .change() event.

var radioSelect = $("input[type='radio']");
var elems = ["q1","q2","q3","q4","q5","q6"];

radioSelect.change(function () {

    // grab the name and value selected radio
    // set localstorage
    var linkName = $(this).attr('name');
    var value = $(this).val();
    localStorage.setItem(linkName, value);

    // I am trying to loop/increment both through the elements
    // and also through the #response[x] divs.
    if (link_name === elems[1]) 
    {
        $("#response1").html(localStorage.getItem(linkName));
    } 
    else if (link_name === elems[2]) 
    {
        $("#response2").html(localStorage.getItem(linkName));
    }  
    else if (link_name === elems[3]) {
        $("#response3").html(localStorage.getItem(linkName));
    }
});

Basic HTML

<input type="radio" name="q2" value="Yes">
<input type="radio" name="q2" value="No">

Upvotes: 0

Views: 41

Answers (2)

Joey Grisafe
Joey Grisafe

Reputation: 415

elems.forEach(function(elem){
  if (linkName === elem) {
   $("#response" + elem.substring(1)).html(localStorage.getItem(linkName));
  }
})

Upvotes: 0

Ngoan Tran
Ngoan Tran

Reputation: 1527

You can replace if/else by for loop as below:

var radioSelect = $("input[type='radio']");
var elems = ["q1","q2","q3","q4","q5","q6"];

radioSelect.change(function () {

    // grab the name and value selected radio
    // set localstorage
    var linkName = $(this).attr('name');
    var value = $(this).val();
    localStorage.setItem(linkName, value);

    // I am trying to loop/increment both through the elements
    // and also through the #response[x] divs.
    for( var i=1; i<=elem.length; i++){
        if (link_name === elems[i]){
            $("#response"+i).html(localStorage.getItem(linkName));
            break;
        } 
    }
});

Upvotes: 1

Related Questions