Search code examples
javascriptjqueryvariablestargeting

Get all Jquery variables beginning with "blank"


all! I've come across a dilemma. I'm creating something of a price-configurator, and basically Jquery is going to be creating a bunch of subtotal variables as the user selects certain options. All of these variables will have names that begin with sub- At the end of the code, I'd like to be able to write a line that gets each one of the sub- variables and adds its value to a grand total. Is there a way to do this, and if so, how?


Solution

  • There is not really a way to do this if the variables are tracked separately. If you stored them in an object, you can loop through the object using

    $.each(myObject, function (key, value) { 
        if (key.indexOf('sub-') === 0) { 
            // to do 
        } 
    });
    

    You can do this with an array, and use

    myArray[myArray.length] = value
    

    as you are looping through the form. Then loop through the array at the end to get the values you need.