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 price in an input field to the default price of the item selected. How exactly would I go about doing this with Javascript? Thanks in advance.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
HTML:
<select>
<option>Select an item</option>
<option data-price="20.00" value="1">Item 1</option>
<option data-price="15.00" value="2">Item 2</option>
<option data-price="24.00" value="3">Item 3</option>
</select>
<input type="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/
回答2:
Using jQuery, you can do something like this:
$("#DropDownId").change(function ()
{
var selectedItem = $(this).val();
if (selectedItem != null && selectedItem != '')
{
$("#InputId").val(selectedItem);
}
});
回答3:
Get all the things you need to display from your server (preferably in JSON)
and generate your select
elements like this..
<select id="mySelect">
<option name="item1ID" defaultPrice="defaultPrice1" >ItemName1</option>
<option name="item2ID" defaultPrice="defaultPrice2" >ItemName2</option>
<option name="item3ID" defaultPrice="defaultPrice3" >ItemName3</option>
<option name="item4ID" defaultPrice="defaultPrice4" >ItemName4</option>
<option name="item5ID" defaultPrice="defaultPrice5" >ItemName5</option>
</select>
You can get default price like
$("#mySelect").on('change',function(){
alert($(this).attr('defaultPrice');
});
回答4:
Whats your server side language?
I would just do something like this:
<script language="javascript">
var items = new Array();
<?
$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.
回答5:
Create Select dropdown menu like below where option value = price of item
<select name="item_list" id="item_list" onchange="update_txt()">
<option value="">Select item</option>
<option value="10"> item1</option>
<option value="20">item2</option>
</select>
<input type="text" id="item_price" value="">
JS:
function update_txt(){
price = document.getElementById('item_list').selectedIndex.value;
document.getElementById('item_price').value = price;
}