Create a dynamic selection field when you select a different selection field

This is my main page where I select the parameter field.

opt1.php:

<html>
<div>
  <select  id="mn" onchange = "show(this.id)" >
    <option value="3">hello</option>
    <option value="4">hiii</option>
    <option value="5">byee</option>
  </select>
</div>
<?php include 'OPT2.php'?>
</html>

This is my javascript where I get the value from above and select opt2.php

function show(s1){
  var s1 = document.getElementById(s1);
  var ch = s1.value;
  $.post('OPT2.php', {variable: ch});
}

This is my opt2.php page for displaying subblock selection.

<?php
  $con = @$_POST['ch'];
  echo "SELECT MODEL:<select id=sb name=sb >";
  echo "<option name=$con>$con</option>";
  echo "</select>";
?>

In fact, this does not create the expected result.

Is there a logical error or a processing error?

+4
source share
1 answer

you need to make an ajax call to opt2.php to get this data so your opt1.php should look like

 <html>
 <div>
            <select  id="s1" onchange = "show(this.id)" >
                <option value="3">hello</option>
                <option value="4">hiii</option>
                <option value="5">byee</option>
            </select>
           <select  id="s2">
                <option>--</option>
            </select>
        </div>
        <?php include 'OPT2.php'?>
</html>

and your javascript

<script type="text/javascript">
    $("#s1").change(function(){
    $('#s2').find('option').remove().end(); //clear the city ddl
    var block_no = $(this).find("option:selected").text();
    var s1 = document.getElementById(s1);
    var ch = s1.value;
    //do the ajax call
    $.ajax({
        url:'OPT2.php',
        type:'GET',
        data:{variable:s1},
        dataType:'json',
        cache:false,
        success:function(data)
        {
        //data=JSON.parse(data); //no need if dataType is set to json
         var ddl = document.getElementById('s2');                      
         for(var c=0;c<data.length;c++)
              {              
               var option = document.createElement('option');
               option.value = data[c];
               option.text  = data[c];                           
               ddl.appendChild(option);
              }

    },

        error:function(jxhr){
        alert("Pls Reload the page");
    }
    }); 
});

0
source

Source: https://habr.com/ru/post/1624110/


All Articles