How to make a combobox insert text depending on the choice?

2

I'm using the help of a post here from OS .

The difference is that instead of having several options to choose from in the other combobox, I only have one option in the database, which should already be entered in the input, when selecting the related.

The code I'm using:

<?php include 'conn.php'; ?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Combos Dependentes</title>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
</head>
<body>
<select id="CmbUF"> 
    <option value="">Selecione a UF</option>
    <?php
        foreach($pdo->query('SELECT ufid, uf FROM ufs order by uf') as $row){
            echo '<option value="'.$row['ufid'].'">'.$row['uf'].'</option>';
        }       
    ?>
</select>
<select id="CmbCidade"> 
</select>
<script type="text/javascript">
    $(document).ready(function() {
        $('#CmbUF').change(function(e) {
            $('#CmbCidade').empty();
            var id = $(this).val();
            $.post('call_cidades.php', {ufid:id}, function(data){
                var cmb = '<option value="">Selecione a Cidade</option>';
                $.each(data, function (index, value){
                    cmb = cmb + '<option value="' + value.cidadeid + '">' + value.cidade + '</option>';;
                });
                $('#CmbCidade').html(cmb);
            }, 'json');
        });
    });
</script>
</body>
</html>

DO Call Cities.php:

<?php       
    if (isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && $_SERVER["HTTP_X_REQUESTED_WITH"] === "XMLHttpRequest"){
        include 'conn.php';
        $ufid = filter_input(INPUT_POST, 'ufid', FILTER_SANITIZE_NUMBER_INT);
        if ($ufid){
            $query = $pdo->prepare('SELECT cidadeid, cidade FROM cidades where ufid=? ORDER BY cidade');
            $query->bindParam(1, $ufid, PDO::PARAM_INT);
            $query->execute();          
            echo json_encode($query->fetchAll());
            return;
        }       
    }
    echo NULL;
    
asked by anonymous 14.06.2017 / 17:26

1 answer

0

Use $('#valor').val(JSON.stringify(data)); to set the input value to a json string.

  • $('#valor') selects input
  • .val(...) arrow value
  • JSON.stringify(data) transforms the object into a string.

If you want to access a property of this object you can do for example

$('#valor').val(data.valorContrato);
    
14.06.2017 / 19:55