0

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">

2 Answers 2

1

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;
        } 
    }
});
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.