Im trying to get selected value from whichever option I pick among the list. However, it mentioned as "Undefined"
<fieldset data-role="controlgroup">
<legend>Select Pizza Flavor </legend>
<select name="flavorlist" id="flavorlist" onclick="total()">
<option value= "">-Select Flavor-</option>
<option value="6">Cheezy Chicken (RM6)</option>
<option value="6">Spicy Chicken (RM6)</option>
<option value="5">Hawaii (RM5)</option>
<option value="6">Peperroni (RM6)</option>
<option value="5">Seafood (RM5)</option>
<option value="5">Beef (RM5)</option>
</select>
</fieldset>
javascript
function flavorprice()
{
var flavorprice = 0
var list = document.getElementsByName("flavorlist");
flavorprice = list.value;
return flavorprice;
}
I tried
function flavorprice()
{
var flavorprice = 0
var list = document.getElementsByName("flavorlist");
flavorprice = list.options[list.selectedIndex].value;
return flavorprice;
}
Still no value. How to fix this? I'm learning jquery mobile. I'm not used with $ yet since I'm really new to this subject.
CodePudding user response:
The issue is because getElementsByName() returns a NodeList, not an Element. Therefore the value property is undefined.
To fix the immediate issue you can instead select the element by its id, as this should be unique in the DOM and will only return a single Element:
function flavorprice() {
return document.getElementById("flavorlist").value || 0;
}
However note that as you're using jQuery mobile, then you can use jQuery methods to achieve the same thing:
function flavorprice() {
return $('#flavorlist').val() || 0;
}
// ES6 version of the above:
let flavorprice = () => $('#flavorlist').val() || 0;
