niq
niq

Reputation: 137

How to display a text after selecting an item name in the dropdown list, the text to be displayed is not the value of select

I wanted to display the description of an item after selecting the item name in the dropdown. I saved the values of the items with its corresponding description in an array using php. so this is my code in php (it is inside a loop):

$item_name[] = ucfirst($row['item_name']);
$desci[] = ucfirst($row['descr']);

Then I have this script (which is not working)

function updateText(val) 
    {
        var $el = document.getElementById("adv1");
        for($i=0; $i < <?php echo $ctr ?>; $i++)
        {
            if(val == '<?php echo "'.$itemid[$i].'" ?>')
            {
                $el.value = "$ 750";
            }
            else
            {
                 $el.value = "0";
            }
        }
    } 

and here is my html code

<select name="item" id="datetime"  onchange="updateText(this.value)"  autofocus required>';
for ($i=0; $i < $ctr; $i++) { 
    echo '  <option value="'.$itemid[$i].'">'.$item_name[$i].' '.$brand[$i].' </option>';
}

echo '</select><p id="adv1"> </p>';

I was wondering how to retrieve the data from php and use it in javascript. Sorry, newbie here. Any help is appreciated, TIA!

Upvotes: 0

Views: 101

Answers (2)

Naisa purushotham
Naisa purushotham

Reputation: 913

 <?php

    echo    '<select name="item" id="datetime"  onchange="updateText(this.options[this.selectedIndex].getAttribute(\'data-val\'))"  autofocus required>';  
    for ($i=0; $i <$ctr; $i++) { 
        echo '  <option value="'.$itemid[$i].'" data-val="'.$desci[$i].'">'.$item_name[$i].' '.$brand[$i].' </option>';
    }
    echo '</select><p id="adv1"> </p>';
?>


 <script>
    function  updateText(nttest){
        document.getElementById("adv1").innerHTML=nttest;
    }
 </script>

hope it will help, In data-val you can pass value what you need to display in adv1

Upvotes: 1

Rico_93
Rico_93

Reputation: 108

You need to use ajax , ajax is simple to use , just follow the example on this link , it just refreshes the div so you don't have to refresh the entire page just to display something

http://www.w3schools.com/ajax/

Upvotes: 0

Related Questions