简体   繁体   中英

Get text inside <p> tag to a <table>

In PHP this is the output I managed to get from a calculation

<p id="generated">12345678199824,12345678411140,12345678921494,12345678497535,</p>

and I need this values to be as below

<table>
 <tr>
  <td>12345678199824</td>
 </tr>

 <tr>
  <td>12345678411140</td>
 </tr>
.....
</table>

Below is the js script I used

$("#setVal").click(function(event){
    event.preventDefault();
    var noOfImei = parseInt($("#nofoemei").val());
    var imeiList = "";
    if (noOfImei !== 0) {
        for (var i = 0; i < noOfImei; i++) {
            imeiList += $("#binnumber").val() + Math.floor(Math.random()*900000+100000) + ",";
        }

        $("#generated").text("");
        $("#generated").text(imeiList);

        // testing purpose
        console.log(imeiList);
    } else {
        alert("Please add no of IMEI(s) need to generate");
    }
});

-- Please not Im a beginner to PHP and JS and managed to progress this far with help of stackoverflow and tutorials. Thank You.

  $("#generated").text("");
  $("#generated").text(imeiList);
  data = imeiList.split(",")
  var table = document.getElementById("myTable");

  for(let i =0;i<data.length ; i++){
   var row = table.insertRow(i); 
   var cell1 = row.insertCell(0);
  cell1.innerHTML = data[i];
  }

And

<table id="myTable" /> // this in dom

you can get the related string and via split create an array. then add rows like follwing:

 document.getElementById("setVal").addEventListener("click", function(){ let table = document.getElementById("myTable"); let nums = document.getElementById("generated").innerHTML; if(nums){ nums.split(',').forEach(i=> { let row = table.insertRow(0); let cell1 = row.insertCell(0); cell1.innerHTML = i; }) } });
 <p id="generated"> 12345678199824,12345678411140,12345678921494,12345678497535,</p> <input type="button" id="setVal" value="Set Rows"/> <table id="myTable" style="border: 1px solid red;"> </table>

In terms of PHP initially you must explode your string and then by counting the string length it becomes more simpler to add a for loop

<?php
$str = "12345678199824,12345678411140,12345678921494,12345678497535";
$str1 =  explode(",",$str);
$arrlength=count($str1);
?> 
<table style = "border:1px solid;border-collapse : collapse;">
<?php
for($x=0;$x<$arrlength;$x++)
  {
  ?>
 <tr style = "border:1px solid;">
 <td style = "border:1px solid;"><?php echo $str1[$x]?></td>
 <tr>

  <?php } ?>
  </table>

Note: Select the correct separator(in this example it is ' , ') in the explode() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM