英文:
Return Select option value in JavaScript
问题
I'd like to return and output to a variable a select option that the user selects in a dropdown menu below.
<h3>Cake Size</h3>
<select id="cakeSize">
<option value="6">6" Cake</option>
<option value="8">8" Cake</option>
<option value="10">10" Cake</option>
<option value="12">12" Cake</option>
</select>
<button type="button" id="calc">Calculate</button>
I want to get 6/8/10/12
into a variable.
const calc = document.getElementById('calc');
let cakeSize = document.getElementById('cakeSize');
let value = cakeSize.value;
calc.addEventListener('click', function test(){
return alert(value);
});
Would like to do this initially using a button event listener to trigger the collection of the value.
英文:
I'd like to return and output to a variable a select option that the user selects in a dropdown menu below.
<h3>Cake Size</h3>
<select id="cakeSize">
<option value="6">6" Cake</option>
<option value="8">8" Cake</option>
<option value="10">10" Cake</option>
<option value="12">12" Cake</option>
</select>
<button type="button" id="calc">Calculate</button>
I want to get 6/8/10/12
into a variable.
const calc = document.getElementById('calc');
let cakeSize = document.getElementById('cakeSize');
let value = cakeSize.value;
calc.addEventListener('click', function test(){
return alert(value);
});
Would like to do this initially using a button event listener to trigger the collection of the value.
答案1
得分: 0
如果您想要“警告”所选的值,请使用alert(cakeSize.value)
。let value = cakeSize.value;
仅具有初始的“select”值。
英文:
If you want to alert
the selected value, use alert(cakeSize.value)
. let value = cakeSize.value;
will have only the initial select
value.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let cakeSize = document.getElementById('cakeSize');
// let value = cakeSize.value;
calc.addEventListener('click', function test() {
return alert(cakeSize.value);
});
<!-- language: lang-html -->
<h3>Cake Size</h3>
<select id="cakeSize">
<option value="6">6" Cake</option>
<option value="8">8" Cake</option>
<option value="10">10" Cake</option>
<option value="12">12" Cake</option>
</select>
<button type="button" id="calc">Calculate</button>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论