Javascript won't read from "select" in a form -
i trying code read value based off selected item select list in form, says it's undefined. when give function value , tell return value, reads, won't take values form.
the following code i'm using
for form (in html):
<form action="" id="orderform" name="orderform" onsubmit="return false;"> <select id="item" name='item' onchange="calculatecost()"> <option value="none">select item</option> <option value="candlestick">candlestick ($10)</option> <option value="bowl">bowl ($10)</option> <option value="burl_bowl">burl bowl ($20)</option> <option value="clock">clock ($15)</option> <option value="vase">vase ($5)</option> <option value="pen">pen ($2)</option> <option value="top">spinning top ($1)</option> </select> <div id="totalprice">hallo</div> </form>
and javascript reads
function calculatecost() { var orderprice = getitemprice(); document.getelementbyid('totalprice').innerhtml = orderprice; } var item_prices= new array(); item_prices["none"]=0; item_prices["candlestick"]=10; item_prices["bowl"]=10; item_prices["burl_bowl"]=20; item_prices["clock"]=15; item_prices["vase"]=5; item_prices["pen"]=2; item_prices["top"]=1; function getitemprice() { var itemprice = 0; var theform = document.forms["orderform"]; var selecteditem = theform.elements["item"]; itemprice = item_prices[selecteditem.value]; return itemprice; }
htmlcollection.item()
method ofhtml select element
returns specific node @ given zero-based index list. returns null if index out of range.
theform.elements["item"]
return function expression of htmlcollection.item
, causing undefined
value theform.elements["item"]
not have property value
either pass this
in inline-event
or use other id
, name
attribute select element item
function calculatecost(elem) { var orderprice = getitemprice(elem.value); document.getelementbyid('totalprice').innerhtml = orderprice; } var item_prices = []; item_prices["none"] = 0; item_prices["candlestick"] = 10; item_prices["bowl"] = 10; item_prices["burl_bowl"] = 20; item_prices["clock"] = 15; item_prices["vase"] = 5; item_prices["pen"] = 2; item_prices["top"] = 1; function getitemprice(val) { var itemprice = 0; itemprice = item_prices[val]; return itemprice; }
<form action="" id="orderform" name="orderform" onsubmit="return false;"> <select id="item" name='item' onchange="calculatecost(this)"> <option value="none">select item</option> <option value="candlestick">candlestick ($10)</option> <option value="bowl">bowl ($10)</option> <option value="burl_bowl">burl bowl ($20)</option> <option value="clock">clock ($15)</option> <option value="vase">vase ($5)</option> <option value="pen">pen ($2)</option> <option value="top">spinning top ($1)</option> </select> <div id="totalprice">hallo</div> </form>
edit: or use getelementbyid
=> var selecteditem = document.getelementbyid('item');
access select
element.fiddle here
Comments
Post a Comment