[Solved]Assign label value when selecting product in combobox

Asked

Viewed 516 times

0

Good morning,

I have this form where comboboxes already show the desired values: [! [Fromulary][1]][1]

Now I have a problem, because I while selecting the product, I want it to appear on the label "Unit" automatically the product unit.

This is the code I used to fill the combobox "Product":

<form name="Registo" action="conexao.php" method="POST">
<b>Produtos:</b>
<br>
<select name="select_Produtos">
<option>Selecione</option>
<?php
$result_Produtos = "SELECT * FROM Produtos";
$resultado_Produtos = mysqli_query($conn, $result_Produtos);
while($row_Produtos = mysqli_fetch_assoc($resultado_Produtos)){ ?>
<option value="<?php echo $row_Produtos['ID']; ?>"><?php echo $row_Produtos['Product']; ?>
</option> <?php
}
?>
</select><br>

And now it’s the code of the rest of the form:

<b>Unidade:</b>
<br>
<input type="text" name="TipoUnid" size="20"><br>
    <b>Quantidade:</b>
<br>
<input type="text" name="Amount" size="5"><br>
<b>Observações (Opcional):</b>
<br>
 <textarea name="Comments" cols="30" rows="5"> </textarea><br>
<b>Quarto (Opcional):</b>
<br>
<select name="select_Bedroom">
<option>Selecione</option>
<?php
$result_Quarto = "SELECT * FROM Quarto";
$resultado_Quarto = mysqli_query($conn, $result_Quarto);
 while($row_Quarto = mysqli_fetch_assoc($resultado_Quarto)){ ?>
<option value="<?php echo $row_Quarto['ID']; ?>"><?php echo $row_Quarto['Bedroom']; ?>
</option> <?php
}
?>
</select><br>
<br>
<input type="submit" name="adicionar" value="Adicionar">
</form>    

Can someone help me?

CREATE TABLE `Estado` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `IDProd` int(11) NOT NULL,
  `Active` tinyint(1) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=latin1;

CREATE TABLE `Quarto` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Bedroom` int(11) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=latin1;
CREATE TABLE `Unidades` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Description` varchar(30) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;

CREATE TABLE `Registo` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `RegistrationDate` date NOT NULL,
  `IDProd` int(11) NOT NULL,
  `Product` varchar(50) NOT NULL,
  `Active` tinyint(1) NOT NULL,
  `IDUnid` int(11) NOT NULL,
  `TipoUnid` varchar(30) NOT NULL,
  `Amount` varchar(20) NOT NULL,
  `Badroom` varchar(15) DEFAULT NULL,
  `Comments` longtext,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1530 DEFAULT CHARSET=latin1;

CREATE TABLE `Produtos` (
  `ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Product` varchar(50) NOT NULL,
  `IDDesc` int(11) NOT NULL,
  `Description` varchar(30) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=64 DEFAULT CHARSET=latin1;

Good morning, I still can not solve my problem, someone can help?

I leave here the link that allowed me to resolve this situation: [https://www.youtube.com/watch?v=_9RXHMn57Gk][2]

But even solving the situation with this video, I thank the community for giving me important tips to reach the solution

  • And what the value of unity and where it comes from?

  • the unit value comes from the mysql database. The product combobox query comes from the products table and only has the id and product fields and the unit comes from the Unid type table and has the id, unit and idprod fields which is equal to the product id.

  • you’ll have to use jquery with ajax to do this

  • And can you set an example for me to try to do? This is the first time I’m doing this

2 answers

1

Surely you will need to implement the solution with Javascript, but the use of AJAX is unnecessary. You do not need to make a request to the server anymore to get only a value you already know initially. The easiest solution I see in this situation is to store the respective unit value in an attribute data option and search it with Javascript when selecting certain value.

For example, the HTML currently generated by your code is something like:

<select name="select_Bedroom" id="select_Bedroom">
    <option>Selecione</option>
    <option value="1">Quarto 1</option>
    <option value="2">Quarto 2</option>
    <option value="3">Quarto 3</option>
</select>

Let’s assume the description of room 1 is x, of room 2 is y and Room 3 is z, then what you can do is create the following HTML:

<select name="select_Bedroom" id="select_Bedroom">
    <option>Selecione</option>
    <option value="1" data-desc="x">Quarto 1</option>
    <option value="2" data-desc="y">Quarto 2</option>
    <option value="3" data-desc="z">Quarto 3</option>
</select>

Understand the definition of the attribute data-desc with their values in the elements option. This you can define with PHP itself:

<option value="<?=$row_Quarto['ID']; ?>" data-desc="<?= $row_Quarto['Description'] ?>"><?=$row_Quarto['Bedroom']; ?></option>

With Javascript, then you can handle the event change of the element select, retrieve the selected option and check the attribute value data-desc. This can be done as follows:

// Objeto para manipulação do DOM:
const select = document.getElementById("select_Bedroom");

// Atribui a função ao evento `change`:
select.addEventListener("change", function (event) {

    // Seleciona a opção selecionada:
    let selectedOption = this.options[this.selectedIndex];

    // Exibe o valor de `data-desc` da opção selecionada:
    console.log("A unidade da opção selecionada é: " + selectedOption.dataset.desc);
});

See example working:

// Objeto para manipulação do DOM:
const select = document.getElementById("select_Bedroom");

// Atribui a função ao evento `change`:
select.addEventListener("change", function(event) {

  // Seleciona a opção selecionada:
  let selectedOption = this.options[this.selectedIndex];

  // Exibe o valor de `data-unidade` da opção selecionada:
  console.log("A unidade da opção selecionada é: " + selectedOption.dataset.desc);
});
<select name="select_Bedroom" id="select_Bedroom">
  <option>Selecione</option>
  <option value="1" data-desc="x">Quarto 1</option>
  <option value="2" data-desc="y">Quarto 2</option>
  <option value="3" data-desc="z">Quarto 3</option>
</select>

This way, you just feed the other form field with the value obtained and this can be done through Javascript as well.

// Objeto para manipulação do DOM:
const select = document.getElementById("select_Bedroom");
const unidade = document.getElementById("unidade");

// Atribui a função ao evento `change`:
select.addEventListener("change", function(event) {

  // Seleciona a opção selecionada:
  let selectedOption = this.options[this.selectedIndex];

  // Define o valor da unidade como sendo `data-desc`:
  unidade.value = selectedOption.dataset.desc;
});
<select name="select_Bedroom" id="select_Bedroom">
  <option>Selecione</option>
  <option value="1" data-desc="x">Quarto 1</option>
  <option value="2" data-desc="y">Quarto 2</option>
  <option value="3" data-desc="z">Quarto 3</option>
</select>

<input type="text" id="unidade" />

  • But then I will have to do this: <option value="1" date-unit="x">Room 1</option> <option value="2" date-unit="y">Room 2</option> <option value="3" date-unit="z">Room 3</>option for each of the products?

  • I commented on how to do PHP, was there any doubt about that? I didn’t understand what these would be produtos.

  • Right now I’m totally lost, I’m not getting anything

  • Some part of the answer you couldn’t understand?

  • is a little confused, sautéed code, I don’t even know where to apply it. It’s the second day I’m fiddling with php...but I really wanted to solve this problem. if you could send a right example to be able to apply and understand would be very grateful friend

  • Which column has the unit value?

  • i have table products that have columns: id (which is the product id), Product, Iddesc (which is the unit id) and Description (unit description). In my form I already have the product combobox to receive the name of each product to select, and when selecting wanted the label after the Unit to assume the value of the column Description (which is the unit description). Gave to understand?

  • @Bruno gave a small edited, see if it helped in something, if not, try to describe which parts became difficult to understand that I try to improve.

  • Do I have to use both codes or just the second part of the code? If I have to use the first part where I apply it?

  • All the HTML codes I used in the answer are examples to create a verifiable answer. You should adapt to your problem using the PHP code I mentioned. You have already made a while to display the options, simply add the attribute data-desc as I described. Javascript code, yes, you will need to embed in your application basically the way you are or adapting as needed.

  • Anderson Carlos woss, find yourself present to help me?

  • Anderson, I am not being able to solve the other situation, can put a link to exemplify this example you gave me to put it into practice?

Show 7 more comments

-1

The Form

<form name="Registo" action="conexao.php" method="POST">
<b>Produtos:</b>
<br>
<select name="select_Produtos" id="select_Produtos">
<option>Selecione</option>
<?php
$result_Produtos = "SELECT * FROM Produtos";
$resultado_Produtos = mysqli_query($conn, $result_Produtos);
while($row_Produtos = mysqli_fetch_assoc($resultado_Produtos)){ ?>
<option value="<?php echo $row_Produtos['ID']; ?>"><?php echo $row_Produtos['Product']; ?>
</option> <?php
}
?>
</select><br>
<b>Unidade:</b>
<br>
<input type="text" name="TipoUnid" id="TipoUnid" size="20"><br>
    <b>Quantidade:</b>
<br>
<input type="text" name="Amount" size="5"><br>
<b>Observações (Opcional):</b>
<br>
 <textarea name="Comments" cols="30" rows="5"> </textarea><br>
<b>Quarto (Opcional):</b>
<br>
<select name="select_Bedroom">
<option>Selecione</option>
<?php
$result_Quarto = "SELECT * FROM Quarto";
$resultado_Quarto = mysqli_query($conn, $result_Quarto);
 while($row_Quarto = mysqli_fetch_assoc($resultado_Quarto)){ ?>
<option value="<?php echo $row_Quarto['ID']; ?>"><?php echo $row_Quarto['Bedroom']; ?>
</option> <?php
}
?>
</select><br>
<br>
<input type="submit" name="adicionar" value="Adicionar">
</form>    

Jquery + ajax

<script>
        $(document).ready(function() {
        $("#select_Produtos").bind('load change',function() {
        var IDProduto= $(this).val();
            $.ajax({
            url: 'dropAmount.php',
            type: 'POST',
            cache:false,
            data: {IDProduto: IDProduto},
            async: false,
            dataType:'html',
            success: function(data) {
        $("#TipoUnid").html(data);                                                                   
            },
            error: function(jqXHR, textStatus, errorThrown){
            alert(errorThrown);
            }
        });

        });
        });      
    </script>

dropAmount.php

     <?php
      include('conetar.php'); 
      if(isset($_POST['IDProduto'])){
       $IDProduto= $_POST['IDProduto'];
       $query= mysqli_query($conn,"SELECT Unidades.Description FROM Produtos RIGHT JOIN Unidades ON Unidades.ID = Produtos.IDDesc where produtos.ID=$IDProduto");
       while($getDescription = mysqli_fetch_array($query)){
        $Description=$getUnidade['Description'];
        echo '<input type="text" name="TipoUnid" size="5" value="'.$Description.'"><br>';
        }
    ?>

Note: Don’t forget to put the IDs in input and select.

Browser other questions tagged

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