Mark
Mark

Reputation: 7818

JQuery/Javascript to loop through JQuery Mobile sliders and create a JSON string from their values

In my controller, I am dynamically creating slider html to pass to my view - so I end up with multiple sliders (could be 1 slider, could be 20, or any number in between - depending on the query from the database).

I need to associate each slider, with it's ID in the database, and the Price.

ExtraPrices array holds the prices to associate with each slider. ExtraIDs array holds the IDs of each extra item in the database.

I want to create a JSON string, which holds what each slider is set to, and take the ExtraPrice and ExtraID too, so that I have a JSON string, I can send back to my code.

The HTML output is:

 <script>
     var ExtraPrices = [20.00,30.00,50.00];
     var ExtraIDs = [13,19,25];
 </script>

  <label for="slider1">item 1</label>
  <input type="range" name="slider1" id="slider1" min="0" max="10" value="0">
  <label for="slider2">item 2</label>
  <input type="range" name="slider2" id="slider2" min="0" max="10" value="0">
  <label for="slider3">item 3</label>
  <input type="range" name="slider3" id="slider3" min="0" max="10" value="0">

I need to be able to loop through the two arrays, and tie them up with the relative slider value. Psuedo code:

var count = 0;
var strJSon = "["
"RoomName": null,";

$.each('#slider').function(){
    strJSon+= "{"
    strJSon+= "\"ID\": " + ExtraIDs[count] + ",";
    strJSon+= "\"Price\": " + ExtraPrices[count] + ",";
    strJSon+= "\"Number\": " + SliderX.slider("option", "value");
    strJSon+= "},"
}

//Remove last comma
strJSon = strJSon.Substring(0, strJSon.LastIndexOf(","));
strJSon+= "]"

so I end up with strJSon similar to:

[{
"ID":13,"Price":20.00,"Number":4,
"ID":19,"Price":20.00,"Number":2,
"ID":25,"Price":20.00,"Number":5
}]

Can anyone help please, with my Javascript code above, to loop through each slider, and build the JSON string noted above?

Thank you,

Mark

Upvotes: 0

Views: 335

Answers (1)

Andy
Andy

Reputation: 63550

Don't build the JSON yourself, create some objects, add them to an array and then JSON.stringify the results.

var arr = [];

$.each('#slider').function(i) {
  var obj = {
    id: ExtraIDs[count],
    price: ExtraPrices[count],
    number: window['Slider' + i].slider("option", "value")
  };
  arr.push(obj);
});

JSON.stringify(arr);

Upvotes: 4

Related Questions