2013-11-25 36 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

相關問題