-5

i'm having a problem with a split inside a foreach in javascript

var res = data.split(",");
                    res.forEach(function(entry) {
                        var fields = res.split("|");
                        var div = fields[0];
                        var val = fields[1];
                        $("#" + div).html(val);
                    });

can anyone help me understand why this is not working?

matt

TaoPR
  • 5,722
  • 2
  • 23
  • 35
  • 1
    What error it gives to you? – Francisco Romero Jun 16 '15 at 01:00
  • This is [Javascript, not Java](http://stackoverflow.com/questions/245062/whats-the-difference-between-javascript-and-java). Specifically, you appear to be using [jQuery](https://blog.udemy.com/jquery-vs-javascript/) – Huey Jun 16 '15 at 01:16

2 Answers2

1

Try using a for loop

var res = data.split(",");
for(var each in res){
  var fields = res[each].split("|");
  var div = fields[0];
  var val = fields[1];
  $("#" + div).html(val);
}
James McDowell
  • 2,358
  • 1
  • 12
  • 27
0

The problem is res.split("|"); it should be entry.split("|");

var data = "v1|1,v2|2,v3|3"

var res = data.split(",");
res.forEach(function(entry) {
  var fields = entry.split("|"); //here
  var div = fields[0];
  var val = fields[1];
  $("#" + div).html(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="v1"></div>
<div id="v2"></div>
<div id="v3"></div>
Arun P Johny
  • 376,738
  • 64
  • 519
  • 520