0

please help me to achieve this code I wanna to make a dropdown list depended on the selection element using jQuery and JavaScript. here the code :

form.php code:

require_once("$CFG->libdir/formslib.php");

$PAGE - > requires - > jquery();
$PAGE - > requires - > js(new moodle_url($CFG - > wwwroot.
  '/local/regform/classes/forms/validation.php'));
class registration_form extends moodleform {
  //Add elements to form
  public function definition() {
    global $CFG;
    global $DB;
    global $PAGE;
    $mform = $this - > _form; // Don't forget the underscore!

    //Branche info
    $branche = $DB - > get_records_sql('select branche.id,branche.idnumber,branche.name as name from {course_categories} as branche where branche.parent=0');
    $brancheArray = array();
    $brancheArray[0] = "اختر الفرع";
    
    foreach($branche as $row) {
      $key = $row - > id;
      $value = $row - > name;
      $brancheArray[$key] = $value;
    }
    
    $attributes = array('onchange' => 'javascript:branchelist()');
    $mform - > addElement('select', 'branche', 'branche / الفرع', $brancheArray, $attributes);

    //year info
    $yearArray = array("select year");
    $mform - > addElement('select', 'year', 'year / السنة', $yearArray);

javascript/jQuery code on validation.php:

<script src="https://www.jqueryscript.net/demo/Dialog-Modal-Dialogify/dist/dialogify.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.13.1/datatables.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
                    
<script>
  function branchelist(){
    const branche_id = window.$("#id_branche").val();
    alert(branche_id);
    window.$("#id_year").load("getter.php?brancheid=" + branche_id);
  }
</script>
```php
**This is the code that will be load on the target element (#year) in file getter.php:**
```php
<?php 
require_once (__DIR__ .'/../../config.php');
global $DB;

// Get the parameter
$brancheid = optional_param('brancheid',  0,  PARAM_INT);

if($brancheid) {
    // Do your query 
    $query = 'SELECT * FROM {course_categories} WHERE parent = ' . $brancheid;
    $year_array = $DB->get_records_sql($query, null,  $limitfrom=0,  $limitnum=0);

    // echo your results, loop the array of objects and echo each one
    echo "<option value='0'>All Students</option>";

    foreach ($year_array as $year) {
        echo "<option value=".$year->id.">" . $year->name . "</option>";  
    }
}

So I tested the alert function and it works fine but there no data changed on the target element (#year).

any help,

thanks in advance.

I tried to load the content of getter.php by send the parameter brancheid but nothing happend.

function branchelist(){
    const branche_id = window.$("#id_branche").val();
    alert(branche_id);
    window.$("#id_year").load("getter.php?brancheid=" + branche_id);
}

0 Answers0