Search code examples
javascriptjquerymodularitymodular-design

How do i save a string and then use is as a variable name?


I am trying to save a string variable and then use this variable as an other variable.

I am saving a string in the "name" variable that can be "weekly", "monthly" or "quarterly".

and then use is as a "this.weekly" but using the "name" reference. Just for not going through the "swtich" for each case.

This is my code:

    // Update "report" variable onclick checkbox
    checkboxSaveOnChange: function(newCheckbox){

        var name = newCheckbox.checked;


        if (newCheckbox.checked) {
            this.name.push(newCheckbox.value);  
        } else {
            var index = this.name.indexOf('newCheckbox.value'); 
            this.name.splice(index, 1); 
        }

        /*switch (name) {

            case 'weekly': 


            break;

            case 'monthly': 

            break; 

            case 'quarterly': 

            break;

        }*/


        console.log(this.weekly);
        console.log(this.monthly);
        console.log(this.quarterly);
    },

tried using var name = 'this.+'newCheckbox.checked; - doesn't work...

EDIT:

This is still resulting the error:

    // (newCheckbox.checked) ? this.name.push(newCheckbox.value) : this.name.indexOf('newCheckbox.value');
    if (newCheckbox.checked) {
        this[name].push(newCheckbox.value);     
    } else {
        var index = this[name].indexOf('newCheckbox.value'); 
        this[name].splice(index, 1);    
    }

Solution

  • Here's an example to elaborate on the previous answer.

    var thingy = {
      weekly: false,
      monthly: false,
      quarterly: false,
      checkboxSaveOnChange: function(newCheckbox) {
        var value = newCheckbox.value,
            checked = newCheckbox.checked;
        this[value] = checked;
      }
    };
    
    document.getElementsByTagName("button")[0].onclick = function(){
      var cbs = document.querySelectorAll("input[type='checkbox']");
      for(var i=0; i<cbs.length; i++) thingy.checkboxSaveOnChange(cbs[i]);
      console.log(thingy);
    };
    <label><input type=checkbox value=weekly />weekly</label>
    <label><input type=checkbox value=monthly />monthly</label>
    <label><input type=checkbox value=quarterly />quarterly</label>
    <button>do a thing</button>