Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

adding options to a <select> element with innerHTML+= works?

I am trying to display the courses from the chosen term using js, it seems that I should be able to add option with innerHTML+= or with creation a option element and adding it to the selection element, neither methods work. (I checked that the courses array is working perfectly and the function gets called)

PHP:

class Course{
            public $name;
            public $id;
            public $term;
            public $credits;

            function __construct($name,$id,$term,$credits){
                $this -> name = $name;
                $this -> id = $id;
                $this -> term = $term;
                $this -> credits = $credits;
            }
            function getName() {
                return $this->name;
            }
            function getId() {
                return $this->id;
            }
            function getTerm() {
                return $this->term;
            }
            function getCredits() {
                return $this->credits;
            }
        }
        
        try {
            // Establish the database connection
            $db = new PDO("mysql:host=$host;dbname=$dbName", $username, $password);
            
            // Set the PDO error mode to exception
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            
            // Prepare and execute the query
            $query = "SELECT * FROM course";
            $statement = $db->query($query);
            //var_dump($statement);
            
            // Fetch the results as an associative array
            $results = $statement->fetchAll(PDO::FETCH_ASSOC);
            //var_dump($results);

            // Process the results
            foreach ($results as $row) {
                $courseName = $row['courseName'];
                $courseId = $row['courseId'];
                $courseCredits = $row['courseCredits'];
                $courseTerm = $row['courseTerm'];

                
                $course = new Course($courseName,$courseId,$courseTerm,$courseCredits);
                array_push($courses,$course);
                
                // Do something with the retrieved data
                //echo "Course: $courseName | Id: $courseId | Credits: $courseCredits | Term: $courseTerm <br>";
            }
        } catch(PDOException $e) {
            // Display an error message in case of connection failure
            echo "Connection failed: " . $e->getMessage();
        }

        //var_dump($courses);
        $jsonArray = json_encode($courses);

js:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let courses = [];
        class Course {
            constructor(name, id, credits, term) {
                this.name = name;
                this.id = id;
                this.credits = credits;
                this.term = term;
            }
        }
courses = <?php echo $jsonArray; ?>;

function displayClasses(){
    console.log("displayClasses()");
    let term = document.getElementById("term").value;
    let output = document.getElementById("className");

    output.innerHTML="";
    console.log(courses[2].term);
    for (let i = 0; i < courses.length; i++) {
        if (courses[i].term == term) {
            //method 1//
            output.innerHTML+=("<option value='"+courses[i].name+"'>"+courses[i].name+"</option>");
            
            /* method 2
            var opt = document.createElement('OPTION');
            opt.text = courses[i].name;
            opt.value = courses[i].name;
            output.options.add(opt);
            */
        }
    }
}

html:

            <div>
                <label for="term">Term</label>
                <select id="term" onchange="displayClasses();">
                    <option value="term1">1</option>
                    <option value="term2">2</option>
                    <option value="term3">3</option>
                    <option value="term4">4</option>
                </select>
            </div>
            <div>
                <label for="className">Class Name</label>
                <select id="className">
                </select>
            </div>

>Solution :

The code works, depending on the courses array, as Geshode suggested.

courses = [
  { term: "term1", name: "English" },
  { term: "term1", name: "Spanish" },
  { term: "term1", name: "Mandarin" },
  { term: "term2", name: "Physics" },
  { term: "term2", name: "Biology" },
  { term: "term2", name: "Chemistry" },
];

function displayClasses() {
  let term = document.getElementById("term").value;
  let output = document.getElementById("className");

  output.innerHTML = "";
  for (let i = 0; i < courses.length; i++) {
    console.log(term, courses[i].term);
    if (courses[i].term == term) {
      output.innerHTML +=
        "<option value='" +
        courses[i].name +
        "'>" +
        courses[i].name +
        "</option>";

    }
  }
}
<div>
  <label for="term">Term</label>
  <select id="term" onchange="displayClasses();">
<option value="term1">1</option>
<option value="term2">2</option>
<option value="term3">3</option>
<option value="term4">4</option>
  </select>
</div>
<div>
  <label for="className">Class Name</label>
  <select id="className">
  </select>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading