Update Cities Combo with jQuery when editing

Asked

Viewed 712 times

0

I have an error in the update of select of cities, no create works correctly, I select the state and cities are updated. On Edit I can’t update cities according to the selected state. I’ve tried a lot of alternatives, but I can’t, can anyone tell me where I’m going wrong? Below is the code:

(function($){
	$.fn.pega_cidades = function(estado){
			$.ajax({
				type: 'GET',
				url: 'cidades/'+estado,
				dataType: 'json',
        contentType: "application/json; charset=utf-8",
				success: function(data){
					if (data != null) {
					  var obj = data;
					  var selectbox = $('#cidade');
					  selectbox.find('option').remove();
					  $("#select2-chosen-2").text("SELECIONE");
					  $.each(obj, function (i, d) {
					    $('<option>').val(i).text(d).appendTo(selectbox);
					  });
					}
				}
			});
	}; 
})(jQuery);
$(document).ready(function() {
	$('.select2').select2();
	$("#cep").mask('99999-999',{placeholder: "_____-___"});
	$("#cpf").mask('999.999.999-99',{placeholder: "___.___.___-__"});
	$("#cnpj").mask('99.999.999/9999-99',{placeholder: "__.___.___/____-__"});
	$("#telefone").mask('(99) 9999-9999',{placeholder: "(__) ____-____"});
	$("#celular").mask('(99) 99999-9999',{placeholder: "(__) ____-____"});

	$("#estado").change(
		function(){
			var estado = $("#estado").val();
			
			$().pega_cidades(estado);
		}
	);
});

html dos campos

<!-- begin snippet: js hide: false console: true babel: false -->
<div class="form-group required">
  <label for="bairro" class="col-sm-2 control-label">Estado:</label>
  <div class="col-sm-10 {if isset($errors['estado'])}has-error has-feedback{/if}">
    <select class="form-control select2" name="estado" id="estado">
      <option value="">SELECIONE</option>
      {html_options options=$estados selected=$sindicato['estado_id']}
    </select>
  </div>
</div>
<div class="form-group required">
  <label for="cidade" class="col-sm-2 control-label">Cidade:</label>
  <div class="col-sm-10 {if isset($errors['cidade'])}has-error has-feedback{/if}">
    <select class="form-control select2" name="cidade" id="cidade">
      <option value="">SELECIONE</option>
      {html_options options=$cidades selected=$sindicato['cidade_id']}
    </select>
  </div>
</div>

  • You can put your HTML here?

  • Hello Sergio, insert html, thanks for the help.

2 answers

0

I usually do it that way:

function AtualizarCidade(idUf) {
$.ajax({
    url: "/Cidades/_ListaPorUf",
    type: "POST",
    data: { idUf: parseInt(idUf) },
    beforeSend: function () { $("#Cidade").attr("disabled", "disabled"); var options = $("#Cidade"); options.empty(); options.append("<option value=''>Loading...</option>"); },
    success: function (returndata) {

        var options = $("#Cidade");
        options.empty();
        options.append("<option value=''>Selecione...</option>");
        $.each(returndata, function (i, item) {
            options.append("<option value='" + item.Id + "'>" + item.Nome + "</option>");
        });



}).done(function() {
    $("#Cidade").removeAttr("disabled");
});

$(document).ready(function () { $("#Uf").change(function (event) {
        AtualizarCidade($(this).val());
    });});

0

I was able to find out why. Below is what I changed to work.

(function($){
	$.fn.pega_cidades = function(estado){
			var url_atual = window.location.href;
			var resultado = url_atual.split("/");
			var uri = '';
			
			if(resultado[4] == 'edit'){
				uri = '../cidades/';
			}else{
				uri = 'cidades/';
			}	
			
			$.ajax({
				type: 'GET',
				url:  uri+estado,
				dataType: 'json',
        contentType: "application/json; charset=utf-8",
				success: function(data){
					if (data != null) {
					  var obj = data;
					  var selectbox = $('#cidade');
					  selectbox.find('option').remove();
					  $("#select2-chosen-2").text("SELECIONE");
					  $.each(obj, function (i, d) {
					    $('<option>').val(i).text(d).appendTo(selectbox);
					  });
					}
				}
			});
	}; 
})(jQuery);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.