views:

24

answers:

1

So I was offered help with this on another question, but I'm struggling to implement it when my app progresses in complexity...

var gender;
var age;
$("#gender :radio").click(function() {
  gender = $(this).val();
  update();
});
$("#age li").click(function() {
  age = $(this).text();
  $('#children').show();
  update();
});


function update() {
  var text = gender || "";
  if (text.length > 0) {
    text += " -> ";
  }
  text += age || "";
  $("span.jquery_out").text(text);
}

Which is fine, but I'm wanting to add in 12 variables, and I need to have the update() function clock up in a more desirable way.

My vars are:

var gender;
var age;
var children;
var income;
var stage2select;
var day;
var spend;
var categories;
var product;
var price;
var quantity;
var total;

How would I get these to cycle through the update() function with " -> " in-between each one, without over using code?

Thanks, Matt.

A: 

You could change your long variable list to an object and then loop the object like this:

var myObj = {
    gender:'',
    age:'',
    children:'',
    income:'',
    stage2select:'',
    day:'',
    spend:'',
    categories:'',
    product:'',
    price:'',
    quantity:'',
    total:''
};

$("#gender :radio").click(function() {
    myObj.gender = $(this).val();
    update();
});

$("#age li").click(function() {
    myObj.age = $(this).text();
    $('#children').show();
    update();
});

function update() {
    var text = "";
    $.each(myObj, function(i){
        if (this != ''){
            if (text.length){
                text += " -> ";
            }
            text += this;
        }
    });
    $("span.jquery_out").text(text);
}
PetersenDidIt
Thanks, only, "var out" should be "var text" i'm guessing right?
mdskinner
yes it should, I corrected it
PetersenDidIt