将 HTML 下拉菜单值传递给 JavaScript 函数和 onclick 函数调用
Pass HTML dropdown menu values to JavaScript function & onclick function call
我知道这个问题已经以多种方式提出,但它们对我没有帮助,当我尝试调试它时,我遇到了"未定义"的错误。
这很简单:我有一个HTML下拉菜单,上面有几个不同的公制单位,我给每个单位一个值。我想将所选值传递给 JavaScript 函数,该函数将检查公制单位类型,然后将其转换为相应的英制单位。
下拉 HTML:
e<p><span><label for="metric-unit">Select metric unit</label></span>
<select name="metric" id="metric">
<option value="cel">Celsius</option>
<option value="cm">Centimeters</option>
<option value="kg">Kilograms</option>
<option value="ml">Milliliters</option>
</select>
</p>
我的 JavaScript 函数尝试传递值:
metricUnit = document.getElementById("metric").value;
我的第二个问题是关于调用转换函数。我想在选择公制单位并在文本字段中输入数字,然后用户单击提交按钮后执行此操作。我应该调用带或不带参数的函数,特别是如果我使用 getElementById 在任何数学发生之前获取度量单位和数字的值?
会不会是
onlick ="convertMeasure()"
或
onclick = "convertMeasure(metric, numVal)"
假设提交按钮和文本字段的 id 分别为sub
和txt
,并且您有一个默认<option>
,例如"选择单位",value = 0
:
var button= document.getElementById("sub");
button.onclick= function(){
var select= document.getElementById("metric");
metricUnit = select[select.selectedIndex].value; //value selected in select
val = document.getElementById("txt").value; // value entered in text field
if(metricUnit!=0 && !isNaN(val)){ // make sure selected item is not default and the text in textbox is a number
convertMeasure(metricUnit, val); // call your function
}
}
似乎您将单击绑定放在 html 中的某个位置,如下所示
<div onclick='callThisFunction()'> Click on this div </div>
然后在你的javascript中,你可以拥有这个函数。在其中,您可以获取下拉列表的选定值并执行所需的任何逻辑。
<script>
function callThisFunction() {
var dropdown = document.getElementById("metric");
var unit = dropdown.options[dropdown.selectedIndex].value;
var nameOfUnit = dropdown.options[dropdown.selectedIndex].text;
if (unit == "cm") {
// do stuff
} else if (unit == "ml") {
// do stuff
}
// etc.
}
</script>
首先获取你的选择元素
var select = document.getElementById("metric");
然后,您可以从具有所选索引的选项中读取值
var metric = select.options[select.selectedIndex].value;
至于如何调用 convertMeasure() 方法,如果您要动态从多个元素获取值,我会建议使用第一个方法。
这是一个可以玩 http://jsfiddle.net/zEncN/的jsfiddle
相关文章:
- 将字符串作为参数传递给函数onclick event jquery
- 将具有特殊字符的值传递给函数onclick事件
- 如何调用mask()jquery函数onclick
- 脚本不会使用 ajax 函数 onClick 和 $_POST 获取变量
- 如何使用JavaScript函数(onclick)在URL中添加我的“No”或“ID”
- jquery 函数 onclick 和 onload myFunction 不是一个函数
- 我们可以调用两个函数 onClick 事件吗?
- 将值传递给 JavaScript 函数 onclick
- jQuery 函数 onclick (span class) 来自 jquery datepicker
- 调用函数onClick,并将元素's的data-*属性
- 运行函数onclick.正在单击的所有按钮
- 正在启动一个函数onclick(),该函数传递被单击元素的id
- 第二个函数onclick没有被调用
- HTML执行不同的php函数onclick
- 调用javascript函数onclick=“;fn1()”;并且onclick=“;javascript:fn1()&
- 触发javascript函数onclick
- 如何在函数onClick中转换值
- 启动按钮下拉赢得't运行函数onclick
- Javascript更多函数onclick和ClassName
- 向函数'onclick'添加SQL