Skip to content Skip to sidebar Skip to footer

Filling Input Field Based On Dropdown Menu Selection With Javascript

In a MySQL database, I have a table of items with the item's ID, name and default price. I wish to have a form with a drop-down menu of all the items in the table that changes the

Solution 1:

HTML:

<select><option>Select an item</option><optiondata-price="20.00"value="1">Item 1</option><optiondata-price="15.00"value="2">Item 2</option><optiondata-price="24.00"value="3">Item 3</option></select><inputtype="text"id="price">

​ JavaScript (using jQuery):

​$('select').on('change', function() {
    $("select option:selected").each(function () {
        $('#price').val('$' + $(this).attr('data-price'));
    });    
});​​​​​​​​

And see this jsFiddle for a working example: http://jsfiddle.net/chnUn/

Solution 2:

Using jQuery, you can do something like this:

$("#DropDownId").change(function ()
{
    var selectedItem = $(this).val();

    if (selectedItem != null && selectedItem != '')
    {
          $("#InputId").val(selectedItem);
    }      
});

Solution 3:

Get all the things you need to display from your server (preferably in JSON)

and generate your select elements like this..

<selectid="mySelect"><optionname="item1ID"defaultPrice="defaultPrice1" >ItemName1</option><optionname="item2ID"defaultPrice="defaultPrice2" >ItemName2</option><optionname="item3ID"defaultPrice="defaultPrice3" >ItemName3</option><optionname="item4ID"defaultPrice="defaultPrice4" >ItemName4</option><optionname="item5ID"defaultPrice="defaultPrice5" >ItemName5</option></select>

You can get default price like

$("#mySelect").on('change',function(){
alert($(this).attr('defaultPrice');
});

Solution 4:

Whats your server side language?

I would just do something like this:

<scriptlanguage="javascript">var items = newArray();

<?$res = mysql_query("SELECT id, name, price FROM ITEM_TABLE");

while($item_object = mysql_fetch_object($res)) {
    ?>
        items[<?echo$item_object->id; ?>] = "<?echo$item_object->price; ?>";
        ('#item_drop_down').append('<option value=' + <?echo$item_object->id; ?> + '>' + <?echo$item_object->name; ?> + '</option>');
    <?
}

?>

('#item_drop_down').Change('#item_price_input').text(items[('#item_drop_down').value()]);

</script>

where the drop down is item_drop_down and the input you want the price in is item_price_input.

Solution 5:

Create Select dropdown menu like below where option value = price of item

<selectname="item_list"id="item_list"onchange="update_txt()"><optionvalue="">Select item</option><optionvalue="10"> item1</option><optionvalue="20">item2</option></select><inputtype="text"id="item_price"value="">

JS:

functionupdate_txt(){
price = document.getElementById('item_list').selectedIndex.value;
document.getElementById('item_price').value = price;
}

Post a Comment for "Filling Input Field Based On Dropdown Menu Selection With Javascript"