David
David

Reputation: 97

Value disappear after dropdown selected

I've searched around to find the answer of my problem but I didn't find any.

I have a table contain 2 columns: kode_barang (Item ID) and nama_barang (Item Name). Kode_barang is a dropdown option which it's data populated dynamically from another table. Each time user select an option, the name of the item will appear automatically.

Here is my code:

<td>
    <select name='kode_barang' type = "text" id='kode_barang1' onchange="changeValue(this.value)">
    <option>Choose</option>
        <?php
            $sql="SELECT * FROM input_data_barang ";
            $result=mysql_query($sql); 
            $met = "var kode_barang = new Array();\n";  

            while ($row = mysql_fetch_array($result)) {  
            $id=$row["kode_barang"];   
            echo "<OPTION VALUE=$id>$id</option>";
            $met .= "kode_barang['" . $row['kode_barang'] . "'] = {name:'" . addslashes($row['nama_barang']) . "',desc:'".addslashes($row['nama_barang'])."'};\n";  
            } 
        ?> 
    </select>
</td>

<td><input type="text" name='nama_barang' id="nama_barang1"/readonly>
    <script type="text/javascript">
        <?php echo $met; ?>
            function changeValue(id){
            document.getElementById('kode_barang1').value = kode_barang[id].name;
            document.getElementById('nama_barang1').value = kode_barang[id].desc;
        };
    </script>
</td>

Dropdown option and Item ID appear perfectly. The problem is, when I select an Item ID, the name of the ID (nama_barang) appear automatically, but then the Item ID disappear. The dropdown become blank. I need the Item ID persist after option selected so the ID can be saved to the database.

Anybody please help me.

Upvotes: 1

Views: 1514

Answers (1)

Forbs
Forbs

Reputation: 1276

The issue that I can see is that you are assigning kode_barang1 the name stored. kode_barang1 is the name of a SELECT object which uses numbers for the ID so when you assign it, it goes to NULL because a name doesn't exist in the <OPTION>.

Create a new input variable called kode_barang2 and change document.getElementById('kode_barang1').value = kode_barang[id].name;

to document.getElementById('kode_barang2').value = kode_barang[id].name;

And you will see that would work.

Upvotes: 1

Related Questions