2013-11-25 32 views
2

是否有将<option>的名称中的文本传递给php的方法?将选项中的“名称”文本传递给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。

我无法更改选择标签中的值,因为它们用于其他功能。

我已经搜索了很多网站,但他们所说的是关于传递值的文本,而不是名称的文本。

+1

jquery可以帮助你... – Kalpit

+4

_I无法更改选择标记中的值,因为它们用于其他功能。所以你注定要失败。 – Florent

+3

“价值”属性是在标准表单提交中提交的。没有非标准的表单提交选项。所以不行。请改变'value',或者在你的服务器上找出'1'等于“apple”。 – deceze

回答

2

有一个在<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); 
+0

有没有办法传递选定的提醒价值隐藏领域? – Isuru

+0

当然,你需要通过隐藏字段传递警报值.. – Chinmay235

+0

我可以知道如何做,因为我不是一个经验丰富的使用java脚本更改值 – Isuru

1

您通过与AJAX一个单独的函数名称的属性。您所要做的就是向选择标签添加一个ID属性(例如“select1”),并读出所选选项的“textContent”属性(水果大写字母)。然后将函数“sendToServer”传递给select-tag的“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> 

我知道,你问它不完全是,但也许它帮助。

+0

请注意,独立的AJAX请求可能会使这里的架构复杂化。这与在同一POST请求中提交值不完全相同。 – deceze

相关问题