通过javascript从下拉列表中获取值,而不使用表单
我有一个下拉列表,如下所示 HTML和PHP通过javascript从下拉列表中获取值,而不使用表单,javascript,html,Javascript,Html,我有一个下拉列表,如下所示 HTML和PHP <select id="selectform_0"> <option value="0">1</option> <option value="1">2</option> <option value="2">3</option> <option value="3">4</option> <optio
<select id="selectform_0">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
<option value="3">4</option>
<option value="4">5</option>
</select>
<input type="button" onclick="selectValue(<?php echo $id; ?>)
">
1.
2.
3.
4.
5.
是的,你可以
标记
<select id='myselectform' name="selectform_0">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
<option value="3">4</option>
<option value="4">5</option>
</select>
1.
2.
3.
4.
5.
JS
//If you want the values when an action takes place, say, onchange
document.getElementById("myselectform").onchange = function(){
alert(this.value)
}
//Or this way,
var t = document.getElementById("myselectform");
var selectedElem = t.options[t.selectedIndex].value;
//Or if you just want the whole list of values then do something like this,
var t = document.getElementById("myselectform").getElementsByTagName("option");
for(var i=0,len=t.length; i<len; i++)
{
alert(t[i].getAttribute("value"))
}
//如果要在操作发生时获取值,例如onchange
document.getElementById(“myselectform”).onchange=function(){
警报(此.value)
}
//或者这样,,
var t=document.getElementById(“myselectform”);
var selectedElem=t.options[t.selectedIndex].value;
//或者,如果你只想要整个值列表,那么做类似的事情,
var t=document.getElementById(“myselectform”).getElementsByTagName(“option”);
对于(var i=0,len=t.length;i您可以使用jQuery
$("#myselectform").val();
或
试试这个
Javascript
<script>
function selectValue(id)
{
//take select value
alert(selectvalue);
}
</script>
<script>
function selectValue(id)
{
var obj = document.getElementById("selectform_"+id).options[document.getElementById("selectform_"+id).selectedIndex].value;
alert(obj);
}
</script>
函数selectValue(id)
{
var obj=document.getElementById(“selectform”+id)。选项[document.getElementById(“selectform”+id)。selectedIndex]。值;
警报(obj);
}
HTML
1.
2.
3.
4.
5.
我猜OP可能需要纯javascript的答案。问题中没有jquery标记。我理解这一点,但当他写“严格”时,我假设他想要客户端代码而不是服务器端代码。
<script>
function selectValue(id)
{
var obj = document.getElementById("selectform_"+id).options[document.getElementById("selectform_"+id).selectedIndex].value;
alert(obj);
}
</script>
<select id="selectform_0">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
<option value="3">4</option>
<option value="4">5</option>
</select>
<input type="button" onclick="selectValue(<?php echo $id; ?>) ">