1

How can i make a loop like this one in Javascript?

foreach ($viewData['cure'] as $cure) 

In this loop I would like to print the result in JS

$("#new").append('<label for="nice_text">ID Type</label><input type="text" id="nice_text" name="cureIdtype" class="input-text" VALUE="<?php echo (string)$cure["id_type"] ?>"/>');
Mohamad
  • 34,731
  • 32
  • 140
  • 219
Krs
  • 41
  • 1
  • 1
  • 5

7 Answers7

4

You can simply combine both like this

<script type="text/javascript">
<?php foreach ($viewData['cure'] as $cure): ?>
$("#new").append('<label for="nice_text<?php echo $cure["id"] ?>">ID Type</label><input type="text" id="nice_text<?php echo $cure["id"] ?>"/>" name="cureIdtype" class="input-text" value="<?php echo (string)$cure["id_type"] ?>"/>');
<?php endforeach; ?>
</script>

Just make sure your Ids are unique (I added $cure["id"] as an example), you might also wanna change the name="cureIdtype", depending on what you want to do with the input afterwards.

Skwal
  • 2,160
  • 2
  • 20
  • 30
3

Was googling this for myself to see if there was something more elegant than what I have below and didn't see my solution mentioned.

PHP

foreach ( $viewData['cure'] as $cure ) {
    ?>
    // your code from above
    $("#new").append('<label for="nice_text">ID Type</label><input type="text" id="nice_text" name="cureIdtype" class="input-text" value="<?php echo $cure["id_type"]; ?>"/>');
    <?php
}

Javascript

var cures = <?php echo json_encode( $viewData['cure'] ); ?>;
for ( var key in cures ) {
    var cure = cures[key];
    // your code from above modified to use the Javascript variable created
    $("#new").append('<label for="nice_text">ID Type</label><input type="text" id="nice_text" name="cureIdtype" class="input-text" value="'+cure["id_type"]+'"/>');
}
Infineight
  • 498
  • 5
  • 10
2

Following is one of the way you can write or use forEach in Javascript.

const arr = ['value0', 'value1', 'value2'];
arr.forEach(element => {
  console.log(element);
});

Also you can refer this link which helps you to understand difference between for and forEach in javascript.

const arr = ['value0', 'value1', 'value2'];
for (let i in arr) {  
  console.log(arr[i])
}
Viraj Mohite
  • 308
  • 1
  • 13
0

Javascript doesn't have foreach like PHP, you need to use a regular for loop.

var a = ["a", "b", "c"];
for (var index = 0; index < a.length; ++index) {
    console.log(a[index]);
}

(from https://stackoverflow.com/questions/9329446/for-each-in-an-array-how-to-do-that-in-javascript)

Thom Wiggers
  • 6,938
  • 1
  • 39
  • 65
  • As @silentw, stated, there is a .forEach method that can be used to iterate through an array. Reference: http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach – Pea Jan 22 '15 at 18:45
0

If you want to do this in PHP and echo the content to the browser, it would look like this:

foreach ($viewData['cure'] as $cure) {
    echo '$("#new").append("<label for=\'nice_text\'>ID Type</label><input type=\'text\' id=\'nice_text\' name=\'cureIdtype\' class=\'input-text\' VALUE=\'' . (string)$cure['id_type'] . '\'/>")';
}

If you have a JavaScript array and want to handle this there, it would look something like this:

for (var i = 0; i < viewData['cure'].length; ++i) {
    $("#new").append('<label for="nice_text">ID Type</label><input type="text" id="nice_text" name="cureIdtype" class="input-text" VALUE="' + viewData['cure'][i]['id_type'] + '"/>")';
}

These examples are untested, and littered with a variety of single/double quotes and escapes, so I could have made some typos in there.

Nick Coons
  • 3,682
  • 1
  • 19
  • 21
0
var a = ["a", "b", "c", "d"];
a.forEach(function(data) {
    console.log(data);
});

I don't understand what is the problem with your code...

<script>
var array = [];
<? foreach ($viewData['cure'] as $cure) {?>
    array.push(<? echo $cure?>);
<? }?>
array.forEach(function(value){
    $("#new").append('<label for="nice_text">ID Type</label><input type="text" id="nice_text" name="cureIdtype" class="input-text" VALUE="'+value+'"/>')
});

</script>
Netzach
  • 321
  • 2
  • 13
-1

Javascript Array forEach() Method


Description:

Javascript array forEach() method calls a function for each element in the array.

Syntax:

array.forEach(callback[, thisObject]);

Here is the detail of parameters:

  • callback : Function to test each element of the array.
  • thisObject : Object to use as this when executing callback.

Return Value:

Returns created array.

Compatibility:

This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work you need to add following code at the top of your script:

if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
}

Example:

<html>
<head>
<title>JavaScript Array forEach Method</title>
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
}

function printBr(element, index, array) {
  document.write("<br />[" + index + "] is " + element ); 
}

[12, 5, 8, 130, 44].forEach(printBr);
  
</script>
</body>
</html>

This will produce following result:

[0] is 12
[1] is 5
[2] is 8
[3] is 130
[4] is 44 

To understand it in better way you can Try it yourself.

SOURCE

Community
  • 1
  • 1
silentw
  • 4,835
  • 4
  • 25
  • 45