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

Asked

Viewed 156 times

2

I’m using the help of a post here in the OS.

The difference is that instead of having several options to choose in the other combobox, I only have one option in the bank, which should already be inserted 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;

1 answer

0


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

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

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

$('#valor').val(data.valorContrato);

Browser other questions tagged

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