0

I edited my question and started afresh.

I have a html form which contains 2 dropdown lists (#selProvincie, #selRegiune). when a new option from List1 is selected by user, List2 must change accordingly. The lists are generated thru PHP from MySQL querying two tables that have a foreign key relationship (this code is not shown for brevity).

HTML

<div class="input_frm">
 <form method="post" action="<?php print data_clean($_SERVER["PHP_SELF"]);?>">
<table class="input_tbl">
   <tr>
      <td class="a">Select province</td>
      <td class="b"><select id="selProvincie" name="Alfa" onchange="provincieChg()"></select></td>
      <td class="c"><input class="button_face" type="submit" value="Submit"></td>
      </tr>
   <tr>
      <td class="a">Select region</td>
      <td class="b"><select id="selRegiune" name="Beta" onchange="regiuneChg()"></select></td>
      <td class="c"></td>
      </tr>
   </table>
</form>

JavaScript

$(document).ready(function()
 {
 $.getJSON("/scripts/031A_GetProvincie.php", success = function(data)
    {
    var str_options = "";
    for (var i=0; i < data.length; i++)
        {
        str_options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
        }

    $("#selProvincie").append(str_options);
    $("#selProvincie").change();

    });

 $("#selProvincie").change(function()
    {
    $.getJSON("/scripts/031B_GetProvRegiune.php?provincie=" + $(this).val(), success = function(data)
       {
       var str_options = "";
       for (var i=0; i < data.length; i++)
           {
           str_options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
       }

     $("#selRegiune").html("");
     $("#selRegiune").append(str_options);
     $("#selRegiune").change();

     });
  });

 $("#selRegiune").change(function()
    {
    $.getJSON("/scripts/031C_GetProvRegiuneZona.php?regiune=" + $(this).val(), success = function(data)
       {
       var str_options = "";
       for (var i=0; i < data.length; i++)
           {
           str_options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
           }

       });
    });

 });

Using the above as an example (I'm new to JavaScript) I want to write a new form, which has a text input field (Text1) inserted between List1 and List2. List2 is generated from the option selected in List1 AND the text in Text1. But I really don't know how to use the process the input text in JavaScript to make the whole thing work.

HTML

<div class="input_frm">
  <form method="post" action="<?php print dataclean($_SERVER["PHP_SELF"]);?>">
    <table class="input_tbl">
      <tr>
         <td class="a">Select county</td>
         <td class="b"><select id="selJudet" name="Alfa" onchange="judetChg()"></select></td>
         <td class="c"><input class="button_face" type="submit" value="Submit"></td>
         </tr>
      <tr>
         <td class="a">Zone wildcard text</td>
         <td class="b"><select id="selText" name="Beta" onchange="textChg()"></select></td>
         <td class="c"></td>
         </tr>
      <tr>
         <td class="a">Select zone</td>
         <td class="b"><select id="selZona" name="Gamma" onchange="zonaChg()"></select></td>
         <td class="c"></td>
         </tr>          
      </table>
   </form>
 </div>

Question: What's the JavaScript for this form ? List2 should change anytime a change occurs in either a new option is selected from List1 OR a new the string in Text1 changes.

6
  • Have you made an attempt at any code? Commented Feb 27, 2016 at 14:37
  • The code is quite complicated and long, although for 3 lists it is repetitive. But the input is a wildcard, and would appear in the php query as such, i.e. we're not talking about three tables bound via foreign key relations. I don't know how to transmit the contents of the text field to the php query for #list2. Commented Feb 27, 2016 at 14:39
  • can you post your of dropdown list and input field code? Commented Feb 27, 2016 at 14:58
  • You need to add a minimized example to the question, without it, it'll be hard to help. Commented Feb 27, 2016 at 14:59
  • As others have said it is difficult to see your specific need, but I am going to go out on a limb. I can show what is needed from a purely jQuery/HTML standpoint to populate the dropdown here: jsfiddle.net/raigsingh/ygrweebj from an AJAX call ... but you would need to make "#list2" more dynamic than what my simple example shows (i.e. my dropdown HTML option is hardcoded) Commented Feb 27, 2016 at 17:07

1 Answer 1

1

Your question is still a little confusing, but I'm working on the assumptions that:

  1. Users will select a country
  2. The available regions will be filtered to show only regions within the selected country
  3. The regions can also be filtered by entering an optional keyword
  4. The "zones" (?) will be filtered based on the above three selections, and displayed to the user

With that in mind, this combination should achieve what you need. I've stripped back the HTML to the bare essentials. I've also change the id of the fields to match (what I think) you're trying to achieve.

The script could be optimised further, but this example should set you on the right path, but let me know if you have additional questions.

I've created a JsFiddle demonstrating how this works.

HTML

<form method="post" action="">  
    Country: <select id="selectCountry" name="Alfa"></select>
    <br>
    Region:  <select id="selectRegion" name="Gamma"></select>
    <br>
    Wildcard: <input id="selectText" name="Beta">
</form>

Javascript

$(document).ready(function() {

    // Change to match your URL
    $.getJSON("/echo/json/", function(data) {
        // Override with fake data because I can't see what the PHP generates
        data = ['Australia', 'Japan', 'Uganda'];

        var str_options = "";
        for (var i=0; i < data.length; i++) {
            str_options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
        }
        $("#selectCountry").append(str_options);
    });

    // Filter regions based on the selected country
    filterRegions = function() {
        country = $("#selectCountry").val();
        wildcard = $("#selectText").val();

        console.log('Search for regions that match ' + country + ' and ' + wildcard);

        // Change to match your PHP url
        $.getJSON(" /echo/json/?country=" + country + "&wildcard=" + wildcard, function(data) {
            // Override with fake data
            data = ['California', 'Florida', 'Nevada'];

            var str_options = "";
            for (var i=0; i < data.length; i++) {
                str_options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
            }
            $("#selectRegion").html(str_options);
        });
    };

    // Filter results based on the selected region and any text search
    filterResults = function(){
        country = $("#selectCountry").val();
        wildcard = $("#selectText").val();
        region = $("#selectRegion").val();

        console.log('Search for zones that match ' + country + ' and ' + wildcard + ' and ' + region);

        // Change to match your PHP url
        $.getJSON("/echo/json/?country=" + country + "&region=" + region + "&wildcard=" + wildcard, function(data) {
            // Display results as you need
        });
    };

    // Attach event handlers to relevant DOM elements (instead of using inline change="Chg()" style functions)
    $("#selectCountry").on("change", filterRegions);
    $("#selectText").on("keyup", filterRegions);
    $("#selectRegion").on("change", filterResults);
});

Notes:

You will need to update the URLs being used for each getJson() request. The URLs will need to pass the values from the <input> and <select> tags as $_GET variables.


In my example, I've used fake data as an example, so remove this from your script when testing it. E.g.

data = ['California', 'Florida', 'Nevada'];

You do not need to specify $_SERVER['PHP_SELF'] because a <form> tag defaults to itself in the absence of any action attribute. E.g.

<form method="post" action="<?php print data_clean($_SERVER["PHP_SELF"]);?>">

Can simply be:

<form method="post" action="">
Sign up to request clarification or add additional context in comments.

4 Comments

Whoops, country or county, I was almost correct! The principle is the same though. List1 can be generated upon page load as I don't think there's any needs or a Ajax request immediately after the page loads. The values will always be the same, won't they? If your List1 data isn't loading, try to use some alert('Loading List1) or console.log('Loading list1') in your testing. Alternatively, you can use console.table(data) to view the results of your Ajax JSON in console.
Thanks. What I actually want is to generate List2 from List1 AND Text1. Data from List1 resides in a MySQL table and is retrieved thru PHP. Text1 is a wildcard, and the MySQL query, executed after I submit the form, would be SELECT... FROM... WHERE County=(here goes option selected from List1) AND Zona LIKE "%(here goes the wildcard string from Text1)%". But now I have a problem generating even List1 and I don't know why. (I checked the PHP separately and it works.) PS. It's county, like in Dade county, but your example is just as good. :)
Yes, actually I debugged the JS script in Mozilla and it won't execute the JSON "success" function, although the PHP script works OK. I'm banging my head against the wall here :). True, I'm very new to JavaScript (2 weeks), although I have 25+ years of programming.
I've just noticed the issue with your getJson() calls. You should not write getJson(url, success = function(data).... It should be getJson(url, function(data)... If you read over the getJSON documentation, you'll see an example at then bottom of the page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.