Select preselected with Jquery change?

0

I'm studying Json and the Jquery change event. What I need is the following When the user opens the page already has results. (no select all checked)

The html comes empty and only works when I change the select to some 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><optionvalue" " selected=" ">todas</option>
  <option value"1"> cidade1</option>
    <option value"2">cidade2</option>
  

</select>

json works perfectly when I select the correct city in the select.

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

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

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

What needs to be changed in the code?

    
asked by anonymous 02.04.2016 / 20:30

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><optionvalue="2"> cidade 2</option>
  <option value="3" >Guamiranga</option>
    <option>Carama</option>
  <option  value=" " selected="selected">Todas</option>

</select>

Hope this helps.

    
02.04.2016 / 21:48