1

I got a question and I am also accepting to getting downvotes for this because I have not really tried something yet. The problem is I don't know how to name the problem and for what I should look for around the internet.

It's like this, I got a link to an api which (in my case) contains all provinces of china in this format:

    {
      "result":{
        "version":"1.0",
        "status":100101,
        "msg":"got provinces successfully"
    },
    "data":[
      {"province":"\u9999\u6e2f"},
      {"province":"\u5317\u4eac\u5e02"}

and some more. Now I want to make a dropdown select menu which contains all this provinces as dropdown values and if one dropdown is selected it should check another URL which says if the selected province is valid or not (in my case it only can be valid because the user cannot enter something himself)

?action=api&i=getCityForProvince&data=北京市

This would be the url for checking this, if it is successful it shows me the cities of the province in the same format like the code above. With this i want to make another select box which only appears if the first is true. In this select box you then select your city and that's it.

I sadly have absolutely no idea how to start with this problem and for what i should look for to solve this.

Henry Vonfire
  • 1,281
  • 10
  • 18
Marcel Wasilewski
  • 2,519
  • 1
  • 17
  • 34

4 Answers4

2

I wonder if the fact that it's chinese has anything to do with your problem? I bet, it doesn't. With jquery it's pretty easy to accomplish such tasks. It's like building blocks you need to put together.

Learn how to make ajax calls with JQuery. It's quite easy, also it should process your Json result, making it a object or array. So in the callback, you can build up your select box like described here. Another block is to bind to the change event of the select box, which is doing another Ajax call (you already know that now) using the value from the Select input. And in the result of that callback, you can also check the result json and if the result was successful, you can easily fill up another select box using already known methods now, or change its visiblity according to your results.

I think you will want to learn those things, and was not supposed to get a ready coded solution :)

Community
  • 1
  • 1
thmshd
  • 5,729
  • 3
  • 39
  • 67
  • Sure i was not excepting someone to code it for me, i want to know it myself. I will go through this now. Thank you! – Marcel Wasilewski Nov 06 '15 at 09:12
  • @thomasjaworski.com If you trie knockout you'd see how it makes it radically easier to bind events, create dom elements, like the select in this case, so and hide elements (the second select) and so on. I'd added a little snippet in my answer so that you can appreciate it. – JotaBe Nov 06 '15 at 09:41
1

To make your work easier, I recommend you to use:

  • a template library
  • an MVVM framework

The difference between using jQuery directly and an MVVM library, or template library, like handlebars or mustache, is that with jQuery you have to take care of handling the elements, and with the other solutions, you leave this work to the framework.

ANyway, I recommend using knockout over using the template libraries, because:

  • it includes the templates
  • it can provide a two-way binding
  • it can handle events
  • it can apply classes, modify visibility, enable and disable elements...

Here I add a simple example of what it can do:

// This is the ko part:   

// This is the view model using Revealing Module Pattern to build it
var vm = (function(){
  // The list of provinces which will be shown when available
  var provinces = ko.observableArray([]);
  // The province selected in the list
  var selectedProvince = ko.observable();
  // This is what you'd call when the provinces are loaded using AJAX
  var loadProvinces = function(data) {
    provinces(data);
  };
  // This functions will be triggered when the selected province changes...
  var updateCities = function() {
    console.log("Here you'd update cities");
  };
  // ... because of this subscription
  selectedProvince.subscribe(updateCities);
  
  // return the object with the desired properties:
  return {
    provinces: provinces,
    selectedProvince: selectedProvince,
    loadProvinces: loadProvinces,
    updateCities: updateCities
  };
})();

ko.applyBindings(vm);


// AJAX call simulation:

// the returned data
var data = [
      {"province":"\u9999\u6e2f"},
      {"province":"\u5317\u4eac\u5e02"}
   ];
   

// a time out to load the data (simulate AJAX call)
setTimeout(function() { vm.loadProvinces(data);}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div data-bind="visible: !(provinces().length)">
  Please wait while loading provinces
</div>                

<div data-bind="visible: provinces().length">
  <select data-bind="options: provinces, 
                     optionsText: 'province',
                     optionsValue: 'province',
                     value: selectedProvince">
  </select>
  <p>Selected province:  <span data-bind="text: selectedProvince"></span></p>
</div>

As you can see, it handles not only creating the DOM elements, bu also handling events, two way-bindig, detecting changes in values...

JotaBe
  • 38,030
  • 8
  • 98
  • 117
0

You could originally write the HTML for your second checkbox and give it a display: none; property. Then on the JS:

if (firstcheckboxValue === true) {

document.getElementById('secondCheckboxId').style='display: block';

}

You could use display: inline-block; or display: inline; etc, whatever suits your layout better.

Anne Bione
  • 19
  • 2
  • that's a beginning, this would at least solve the checbox problem, but the bigger one is to get the data from the other url and returning them as select options to my dropdown box. – Marcel Wasilewski Nov 06 '15 at 08:59
0

Things would drastically get easier if you used jQuery. Since there's no code to start working with, I'll just list out steps I'd go through.

1) Write DOM elements for dropdowns, say #dd_provinces #dd_cities. #dd_cities would be hidden.
2) From $().ready(function(){...}) I'd make the web API call.
3) From result callback of the API call in #2, make the second API call(one to fetch cities of the province).
4) Result callback of the second API callback will populate the DOM element #dd_cities
5) Unhide #dd_cities

Sample code: HTML

<select id="dd_provinces">
</select>
<select id="dd_cities" style="visibility: hidden">
</select>

JS

 $(document).ready(function() {
        $.ajax({
            url: "/echo/json/",
            data: "",
            success: function(evt) {
                var mData = ["City 1", "City 2", "City 3", "City 4"];
                for(var i = 0; i < mData.length; i++){
                    var optionElem = "<option>" + mData[i] + "</option>";
                    $("#dd_provinces").append(optionElem);
                }
                $.ajax({
                    url: "/echo/json",
                    data: "",
                    success: function(evt) {
                       $("#dd_cities").css("visibility", "visible").animate('5000');
                    }
                });
            },
            error: function(evt) {
                console.log(evt);
            }
        });
    });
alok
  • 502
  • 3
  • 15
  • Please, add a little snippet showing the proposed solution – JotaBe Nov 06 '15 at 09:38
  • @JotaBe : My JSFiddle isn't working for some reason, just pasting the code snippet here itself. – alok Nov 06 '15 at 10:00
  • But, even if it's not working (I suppose the problem are your ajax calls) that's enough to show the basic idea behind your answer. To simulate ajas calls in a fiddle, please, see this: http://doc.jsfiddle.net/use/echo.html – JotaBe Nov 06 '15 at 10:17
  • Actually, I'd tested this exact piece of code yesterday, when it worked with JSFiddle. Today, the site itself won't open here. Anyway, I'm glad I could get the idea through :) – alok Nov 06 '15 at 11:10