capture option value with jQuery

6

I have the following select in html.

 <select name='busca' onChange='link()'>
            <option value="1">OP1</option> 
            <option value="2">OP2</option>
            <option value="3">OP3</option>
            <option value="4">OP4</option> 
        </select>    

I need to create a function in jQquey called link where it picks up the value of the select and loads a link, example: envia.php?op=1

Does anyone know how to do this?

    
asked by anonymous 17.11.2016 / 11:44

4 answers

8

It is possible by the jQuery change event to get the value:

$('select[name="busca"]').on("change",function(ev){
  var linkEnviar = "envia.php?op=" + $(this).val();
  console.log(linkEnviar);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="busca" name='busca'>
  <option value="1">OP1</option>
  <option value="2">OP2</option>
  <option value="3">OP3</option>
  <option value="4">OP4</option>
</select>
    
17.11.2016 / 11:47
7

Place logic in jQuery and you can use this.value to know the value of select within a callback of event change like this:

$('select[name="busca"]').on('change', link);

function link() {
    $.ajax({
        method: "POST",
        url: "envia.php",
        data: {op: this.value} // <---- aqui passas o valor
    }).done(function(msg) {
        alert(msg);
    });
}
    
17.11.2016 / 11:48
2

Here's an example. HTML:

$(document).ready(function(){    
  $("#selecao").on("change", teste);
});
var teste = function(evt){
                var valorSelecionado = evt.target.value;
  console.log(evt.target.value);
            }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script><selectid="selecao">
  <option value="1">Opção 1</option>
  <option value="2">Opção 2</option>
  <option value="3">Opção 3</option>
</select>

jQuery:

$(document).ready(function(){document.getElementById("selecao").addEventListener("change", teste);}
var teste = function(evt){
                var valorSelecionado = evt.target.value;
            }
    
06.12.2016 / 20:35
1

Also to do with pure javascript:

<select name='busca' onChange='location.href="envia.php?op="+this.value'>
            <option value="1">OP1</option> 
            <option value="2">OP2</option>
            <option value="3">OP3</option>
            <option value="4">OP4</option> 
        </select>
    
17.11.2016 / 13:27