Select pressed with Jquery change?

Asked

Viewed 379 times

0

I’m studying Json and the Jquery change event. What I need is this When the user opens the page already has results. (in select come marked all)

html comes empty and only works when I change select to a city.

   var cidade = "";

$('select').on('change', function() {


  cidade = this.value


  var url = "http://meusite?&cidade="+cidade;

//jsonrodando
  
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select >
  <option>cidades</option>
  <option value" " selected=" ">todas</option>
  <option value"1"> cidade1</option>
    <option value"2">cidade2</option>
  

</select>

json works perfectly when selecting the right city in select.

But it does not come pre loaded with all. (When the variable "city" in the URL comes empty all appear)

It should work as follows: Open page comes all cities. (this does not work).

User changes in select city, and city appears (this works perfect);

What needs to be changed in the code ?

1 answer

1

Solved. I modified the code.

$( "select" ).change(function () {
    var str = "";
    $( "select option:selected" ).each(function() {
      str += $(this).val() + " ";
    });
    console.log(str);
    cidade=str;

    var url = "http://meusite.com?cidade="+cidade;
  
//json rodando perfeito aqui 

  })
  .change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select  >
  <option value="2"> cidade 2</option>
  <option value="3" >Guamiranga</option>
    <option>Carama</option>
  <option  value=" " selected="selected">Todas</option>

</select>

I hope this helps.

Browser other questions tagged

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