How to select an option from an input select with the value of $_GET with Jquery

Asked

Viewed 88 times

0

The page receives a value for $_GET and would like to auto select the value of a select input equal to the value of $_GET received using Jquery:

<?php
$valor = $_GET['valor']; // valor1
?>

<select name='selectValores'>
    <option value='valor1'>Valor-1</option>
    <option value='valor2'>Valor-2</option>
    <option value='valor3'>Valor-3</option>
</select>

<script>
$(document).ready(function() {

});
</script>

RESOLVED:

<script>
$(document).ready(function() {
    var theValue = '<?php echo $_GET['pesquisa-tipo']; ?>';
    $('#formCaminhaoPesquisa #pesquisaTipo option[value=' + theValue + ']').attr('selected',true);
});
</script>
  • Wouldn’t it be better to do this directly in PHP? So the option is already selected without the need to use jQuery.

  • Not because I need to manipulate DOM and I can’t change PHP unfortunately rsrsrs

1 answer

-1

I suggest switching between double quotes and single quotes, so it will read the variable as a whole:

var theValue = "<?php echo $_GET['pesquisa-tipo']; ?>";

Another solution I would have, would be to put an id in html, to pull the value pro javascript

<select name='selectValores' id="valores">
<option value='valor1' id="valor1">Valor-1</option>
<option value='valor2' id="valor2">Valor-2</option>
<option value='valor3' id="valor3">Valor-3</option>

And in javascript, pull the value through a getElementById

Browser other questions tagged

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