0

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

Mark
  • 7,778
  • 24
  • 89
  • 147

1 Answers1

5

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);
Andy
  • 61,948
  • 13
  • 68
  • 95
  • Hi - thanks - where I have SliderX - how do I get that to look at "slider1", "slider2" etc? – Mark Sep 13 '13 at 14:38
  • You could try the change I just made. I can't guarantee it will work tho. From [here](http://stackoverflow.com/questions/5117127/javascript-dynamic-variable-name). – Andy Sep 13 '13 at 14:43
  • What I would probably do is store the sliders in an array and call them like so: `sliderArray[i].slider('option', 'value');`. No need to number them then. – Andy Sep 13 '13 at 14:54
  • Thanks Andy - I'll mark as the answer just now, as it's got me a lot closer. I'll post another question, specifically around looping through sliders. Cheers for your help, Mark – Mark Sep 13 '13 at 15:11