-2

i have a dynamic table that generates rows when end-user presses a button. I had no problem using it on input boxes. Now im trying to change one input into a combo box that queries data from my db. The problem i have know is how to dynamically add the combo box along with its php code.

$(document).ready(function(){
    var counter = 2;
    $('.add-row').click(function() {
        $(".item_form").append(
            '<tr><td><input type="text" name="serialnoa[]" placeholder="serial no.' +
            counter + '"/></td></tr>'
        );
        counter++; 
    });
    $('.del-row').click(function() {
        if($(".item_form tr").length != 2)
        {
            $(".item_form tr:last-child").remove();
            counter--; 
        }
        else
        {
            alert("You cannot delete first row");
        }
    });
});
<!DOCTYPE html>
<html class="no-js" lang="en" dir="ltr">
  
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">


<link rel="stylesheet" type="text/css" href="_css/inventory.css?v=<?=time();?>">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

</head>

<body>
  
<table class="item_form">
<tr>
  <th>serial no.</th>
  <th>brand<th>
</tr>

<tr>
  <td><input type="text" placeholder="serial no.1" name="serialnoa[]"></td>
  <td>
 <select name="show_brands[]">
 <?php
 mysql_connect('localhost', 'root', 'adminpass');
 mysql_select_db('my_db'); 
 $sql = "SELECT DISTINCT brand FROM warehouse ORDER BY brand";
 $result = mysql_query($sql);

 while ($brand=mysql_fetch_assoc($result)) {
  echo "<option value='".$brand['brand']."'>".$brand['brand']."</option>";
 }
 ?>
 </select>
  </td>
</tr>
</table> 

<table>
<tr>
 <td><a href="#" class="add-row"><div>+ Row</div></td>
 <td><a href="#" class="del-row"><div>- Row</div></td>
         
</tr>
</table>
  
</body>
</html>
Thum Choon Tat
  • 3,084
  • 1
  • 22
  • 24
bongoloids
  • 19
  • 5
  • 1
    You can by `echo '';` using php – Jyothi Babu Araja Nov 18 '16 at 07:17
  • Either load it in a hidden state by default and reveal it on button click or use AJAX to get the database information. – Kilian Stinson Nov 18 '16 at 07:21
  • @JyothiBabuAraja im not sure what your trying to suggest. Im able to replicate/append the combo box. but the query that needs to be passed to populate the options and value thats the problem im facing. What would be the best approach? – bongoloids Nov 18 '16 at 07:21
  • @KilianStinson I want to achieve something that only executes as per appended row. even with this i think its gonna take a toll on processing for querying dynamically. As for ajax im looking for some samples and i think your right. Might as well make the php query external and call it on my script. But I dont know where to begin. can you site a basic sample? – bongoloids Nov 18 '16 at 07:25
  • @bongoloids So you want to add `select` for each `input` and populate that `select` with `db data` using `php` right? – Jyothi Babu Araja Nov 18 '16 at 07:42
  • @JyothiBabuAraja yes thats what im trying to accomplish – bongoloids Nov 18 '16 at 07:44
  • http://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php?rq=1 – Kilian Stinson Nov 18 '16 at 07:45
  • If all `input` s have same `brand`s `select`, then store that `brands` data in `JS array` and populate every `select` the time new `input` is added – Jyothi Babu Araja Nov 18 '16 at 07:52
  • If you want to pass a user click through your script into php you may have a problem. Your PHP renders on pageload. It therefore can't utilize any post rendered jquery user actions. You can pass the jquery user actions into a URL (variable), and then when that URL is loaded you can then load the php with the passed parameters. Or, you can load the PHP through an iframe after the JQuery action. – Michael d Nov 18 '16 at 07:54

2 Answers2

0

I just used a MOCK to populate dynamic select boxes. You need to remove that mock in your server environment. If your DB gives proper data, then populate that data into JavaScript Array. Then you can use that array to populate dynamic select boxes.

function populateSelect(element){
  brands.forEach(function(brand){
    $('<option />', {
      value: brand,
      text: brand
    }).appendTo($(element));
  })
}
$(document).ready(function(){
    populateSelect('select'); //populating first select
 var counter = 2;
     $('.add-row').click(function() {
           $(".item_form").append('<tr><td><input type="text" name="serialnoa[]" id="serialno' + counter + '" placeholder="serial no.' +
         counter + '"/></td><td><select id="select-serialno' + counter + '"></select></td></tr>');
       populateSelect("#select-serialno" + counter ); //populating new select created
   counter++;
     });
   $('.del-row').click(function() {
       if($(".item_form tr").length != 2)
         {
            $(".item_form tr:last-child").remove();
            counter--; 
         }
      else
         {
            alert("You cannot delete first row");
         }
          });
});
</script>
<!DOCTYPE html>
<html class="no-js" lang="en" dir="ltr">
  
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">


<link rel="stylesheet" type="text/css" href="_css/inventory.css?v=<?=time();?>">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

</head>

<body>
  <!--Uncomment below php code in your PHP environment -->
  <!--<?php 
 mysql_connect('localhost', 'root', 'adminpass');
 mysql_select_db('my_db'); 
 $sql = "SELECT DISTINCT brand FROM warehouse ORDER BY brand";
 $result = mysql_query($sql);
    echo '<script>'; //here starts creating new array of brands
    echo 'var brands = []';
 while ($brand=mysql_fetch_assoc($result)) {
  echo 'brands.push("'. $brand['brand'] .'")'; //adding new brand to brand array
 }
    echo '</script>'
 ?> -->
  <script>
    //NOTE: a mock for your DB
  var brands = ["brand1", "brand2"]; //removes this if your php codes works
    </script>
<table class="item_form">
<tr>
  <th>serial no.</th>
  <th>brand<th>
</tr>

<tr>
  <td><input type="text" placeholder="serial no.1" name="serialnoa[]"></td>
  <td>
 <select name="show_brands[]">
 </select>
  </td>
</tr>
</table> 

<table>
<tr>
 <td><a href="#" class="add-row"><div>+ Row</div></td>
 <td><a href="#" class="del-row"><div>- Row</div></td>
         
</tr>
</table>
  
</body>
</html>
Jyothi Babu Araja
  • 10,076
  • 3
  • 31
  • 38
0

tried to look at it in a different way. just added a function to mirror the first populated combobox with the php query.

var counter = 2;
$('.add-row2').click(function() {
$(".release_form").append('<tr><td><select name="show_brands[]" id="unique'+counter+'"></select></td><td><input type="text" name="serialnob[]" placeholder="serial no.' +

  counter + '"/></td></tr>');
  $('#unique'+counter).append($('#unique').html());
  counter++; 
});
bongoloids
  • 19
  • 5