Set the option available for select based on another select php

后端 未结 1 765
南方客
南方客 2020-12-20 05:47

Continent Table

  1. ASIA
  2. SOUTH AMERICA

Country Table

  1. Japan
  2. China
  3. Brazil
  4. Peru

Th

相关标签:
1条回答
  • 2020-12-20 05:57

    Like it was said, you can use ajax. There is a static non-ajax way of doing it, but this way it is better in the long run.

    Basically, what you do with that jQuery is listen for a change in the continent select box, and when a change happens, you make a request to the server asking: "give me all the countries within this continent". You should have a database for this or you can map them in static objects just to test it out.

    $('.continent').change(function() {
        var id = $(this).val(); //get the current value's option
        $.ajax({
            type:'POST',
            url:'<path>/getCountries',
            data:{'id':id},
            success:function(data){
                //in here, for simplicity, you can substitue the HTML for a brand new select box for countries
                //1.
                $(".countries_container").html(data);
    
               //2.
               // iterate through objects and build HTML here
            }
        });
    });
    

    This would of course make you add the countries_container in the HTML like and inside it you would render the select:

    <div class="countries_container"></div>
    

    Now in the actual PHP code server side (getCountries) you could do something like:

    $id = $_POST['id'];
    if(isset($id) && <other validations>)){
    
      // 1. your query to get countries from a given continent
      // and for each result you can build the HTML itself
    
      // 2. OR, a better solution is to return an Object and then in the
      // success:function(data){ } iterate through it
    }
    

    This code can most defiantly be improved, but I tried to explain it in a understandable way.

    Also, you should check:

    Jquery ajax populate dropdown with json response data

    Demo of linked drop down list by using Ajax & PHP

    Keep on mind, these were the first results from a google search therefore, next time, try to search within stack overflow itself to avoid duplicate questions.

    0 讨论(0)
提交回复
热议问题