0

sorry but i am new here and i don't know php very well. I would like to ask how can i generate dynamic textboxes and labels depend on the selection on a popup menu. I want to make a site in wordpress that would have a popup menu that shows titles of the Thesis. I have a database with an array named wp_courses and there are course_id, Thesis_ID, course_title in it ,and an other array named Thesis with Thesis_ID,Thesis_Title.i want when a thesis is chosen to generate textboxes with the specific courses that the thesis have and labels with the title of the courses, to fill. I am confused how can i pass my database in the function.Can i do it with javascript?

//my php code so far

function showTextboxes(choise){
  for(i=0;i<=choise;i++)
     {
        my_div.innerHTML = my_div.innerHTML +"<br>
        <input type='text' name='mytext'+ i>";
     }
           $conn = mysqli_connect("localhost","root","","wordpress"); 
     mysqli_query($conn,'SET NAMES utf8');
          <label class='formLabel'>Title of thesis*</label><br />";
     $query = "SELECT * FROM wp_thesis";
     $result = mysqli_query($conn,$query);
     echo"<select name='ThesisTitle' id='link_block' onChange='showTextboxes(this.selectedIndex);' required=''>
     <option disabled='disabled' selected='selected' value=''></option>";
      foreach ($result as $row)
      {
       echo "<option value= {$row[Thesis_ID]}>      {$row[Thesis_Title]}</option>";
      }
      echo"</select><br />";
                        <div id="my_div"></div>
 



  
Black Widow
  • 75
  • 2
  • 10

1 Answers1

0

It is generally a very good idea to separate your data from the front-end code.

Such as returning it as JSON string.

PHP has a built in function json_encode to do this with mysql results : https://stackoverflow.com/a/383664/5335350

JSON/Object example:

var Thesis = [{
  Thesis_ID: 0,
  Thesis_Title: 'My thesis title1'
}, {
  Thesis_ID: 1,
  Thesis_Title: 'My thesis title2'
}, {
  Thesis_ID: 2,
  Thesis_Title: 'My thesis title3'
}]

With that data is very simple to now accomplish what you want with a little JS & HTML

HTML :

<div id="courses">
  <table>
    <tr></tr>
  </table>
  <hr/>
  <label for="course">Select course: <span></span>
    <input name="course">
  </label>
  <select class="form-control" name="userName">
    <option></option>
  </select>
</div>

JS:

mag.module('courses', {
  view: function(state) {

    state.option = Thesis.map(function(thesis) {
      return {
        _selected: thesis.Thesis_ID == state.index ? true : null,
        _text: thesis.Thesis_Title,
        _value: thesis.Thesis_ID
      }
    });

    state.select = {
      _onchange: function(e) {

        var i = e.target.selectedIndex

        state.span = Thesis[i].Thesis_Title + ' ID:' + Thesis[i].Thesis_ID

      }
    }
  }
});

Here is the full working example: http://jsbin.com/qafupozemu/1/edit?html,js,output

Hope that helps!

Community
  • 1
  • 1
MagJS
  • 422
  • 3
  • 3