有没有办法将<option>
名称中的文本从传递到php?
<form action="process.php" method="post">
<select name="select1">
<option value="1" name="apple">APPLE</option>
<option value="2" name="lemon">LEMON</option>
<option value="3" name="grapes">GRAPES</option>
</select>
<input type="submit" value="submit"/>
</form>
我想把水果的名字用简单的或大写的形式传给php。
我无法更改select标记中的值,因为它们用于另一个函数。
我搜索了很多网站,但他们说的只是传递值的文本,而不是名称的文本。
<option>
标签中没有属性名称
我的代码:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<form action="process.php" method="post">
<select name="select1" id="select1">
<option value="1" name="apple">APPLE</option>
<option value="2" name="lemon">LEMON</option>
<option value="3" name="grapes">GRAPES</option>
</select>
<input type="hidden" id="hidField" name="xyz" value="" />
<input type="submit" value="submit" />
</form>
<script>
//function test(){
var select1= document.getElementById("select1");
$("#select1").change(function(){
//alert(select1.options[select1.selectedIndex].text);
//alert(select1.options[select1.selectedIndex].getAttribute("name"));
var res=select1.options[select1.selectedIndex].getAttribute("name");
document.getElementById('hidField').value=res; //Javascript code
//$('#hidField').val(res); //Jquery code
return false;
});
//}
</script>
如果您确定要名称字段必须存在,请使用getAttribue("name")
而不是text
代码:
alert(select1.options[select1.selectedIndex].getAttribute("name"));
想要获取<option>
标签的内部数据
代码:
alert(select1.options[select1.selectedIndex].text);
您使用AJAX在一个单独的函数中传递名称Attributes。您所要做的就是将ID属性(例如"select1")添加到所选标签中,并读出所选选项的"textContent"属性(大写水果)。然后将函数"sendToServer"传递给select标记的"onchange"事件。
function sendToServer()
{
var select = document.getElementById("select1");
var sel = select.options[select.selectedIndex];
var name = select.getAttribute("textContent");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
}
}
xmlhttp.open("GET", "../PHPScripts/getData.php?q=name", true);
xmlhttp.send();
}
HTML:
<select name="select1" id="select" onchange="sendToServer();">
<option value="1" name="apple">APPLE</option>
<option value="2" name="lemon">LEMON</option>
<option value="3" name="grapes">GRAPES</option>
</select>
<input type="submit" value="submit"/>
</form>
我知道,这并不完全是你所要求的,但也许它会有所帮助。