How can I dynamically drag and drop elements in jquery?

So, I want to make a dynamic little script to select countys and then cities. Well, I have all the counties and cities in the mysql database. If I select a county in the tag <select>, then the cities belonging to the county should appear in the next tag <select>.

So maybe I could do something like

$(document).ready(function() {
  $('.county').click(function(){
    $(this.name).toggle(); 
  });
});

where the countys option might look something like this:

<option value="This County" name="This County" class="county">This County</option>

When I click it above, each city connected to "This County"should appear. You just need to be fined a bit on this one. Does anyone think they can help?

+3
source share
3 answers

select, county select.

$("#counties").change(function(){
   $(".cities").hide();
   $("#" + this.value + "-cities").show();
});

: http://jsfiddle.net/jonathon/upaar/

, , . , . , " " JSON $. Get().

( GeoNames , );

$.get('http://ws.geonames.org/countryInfoJSON', function(data) {
    $.each(data.geonames, function(i, item) {
        $("#countries").append("<option value='" + item.geonameId + "'>" + item.countryName + "</option>");
    });
});

$("#countries").change(function() {
    $("#cities").empty();

    $.get('http://ws.geonames.org/childrenJSON?geonameId=' + this.value, function(data) {
        $.each(data.geonames, function(i, item) {
            $("#cities").append("<option value='" + item.geonameId + "'>" + item.name + "</option>");
        });
    });
});

: http://jsfiddle.net/jonathon/QkXAK/

countries. , . geonameId . cities , AJAX.

, , , . GeoNames , , .

+2

, , , 2 :

  • : $('.' + this.name) $('#' + this.name) .
  • , .

Edit:

, :

HTML:

<select id="counties">
    <option value="">Choose one...</option>
    <option value="the-county">The county</option>
    <option value="the-other-county">The other county</option>
</select>

<div class="city the-county">The city</div>
<div class="city the-county">The second city</div>
<div class="city the-other-county">The other city</div>

javascript:

$(document).ready(function() {
    var showCities = function(county) {
        var $cities = $('.city'),
            $countyCities = county ? $('.city.' + county) : [],
            $otherCities = $cities.not($countyCities);

        $otherCities.hide();
        $countyCities.show();
    }

    $('#counties').change(function() {
        showCities($(this).val());
    });

    // Don't show anything at page load.
    showCities(null);
});
0

:

$(document).ready(function() {
  $('.county').change(function(){
      $.get('/cities', {whichCounty: $(this).val()}, function(html) {
          $('#cities').html(html);         
      });
  });
});

, , whichCounty <select> , #cities.

JSON (, CityId = > CityName), , "" <select>.

- (JSON), .

0
source

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


All Articles