To better meet your need, ie recover the value according to the product selected in the field select
I will present the following solution:
- Make when the value of the
select
is changed, an event is created that triggers a request that returns the value of the product in JSON format.
Follows approach:
<?php
$sql = "SELECT * FROM servicos ORDER BY nome";
$resultado = mysql_query ($sql) or die ("Problema na lista!");
?>
<select name='servico' id="idservico" style="text-transform:uppercase">
<option value=''> Selecione</option>
<?php while ($servico = mysql_fetch_object($resultado)): ?>
<option value="<?php echo $servico->id?>"> <?php echo $servico->nome?> </option>
<?php endwhile ?>
</select>
<br />
<input name="valor" type="text" id="idvalor" />
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type='text/javascript'>
$( document ).ready(function() {
// altera valor do campo
function alteraValorCampo() {
var idservico = $( "#idservico" ).val();
var data = {
"action": "obtervalor",
"idservico" : idservico
};
data = "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "obtemvalor.php",
data: data,
success: function(data) {
$("#idvalor").val(data.valor);
}
});
return false;
}
$( "#idservico" ).change( alteraValorCampo );
alteraValorCampo();
});
</script>
Now, let’s create the archive obtemvalor.php
which will be responsible for recovering the value of the product selected in the field select
.
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checa se valor existe
$action = $_POST["action"];
$id = $_POST['idservico'];
switch($action) {
case "obtervalor": obter_valor_servico($id);
break;
}
}
}
//Funcao que checa se a requisicao ajax e valida.
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function obter_valor_servico($id){
$sql = "SELECT id, valor FROM servicos WHERE id = ".intval($id);
$resultado = mysql_query ($sql) or die ("Problema na lista!");
$linha = mysql_fetch_object($resultado);
echo json_encode($linha);
}
?>
Thus, whenever a service is selected, the value field will receive the value of the service.
Technologies used for solution: Jquery, PHP and AJAX.
I don’t understand. You who, when selecting items in
<select />
, they appear in the<input />
? Like, comma separated, something like that?– Thiago Lunardi
they come dynamically by sql, fill in select. But each select of this, is a service, which contains a value ($). wanted this value to appear in the input when switching service in select options.
– Leandro Guilherme