Reputation: 3184
Is there a way to pass the text in the name of the <option>
to a php from?
<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>
I want to get the fruits name in simple or capital passed to the php from.
I cannot change the values in the select tag because they are used for another function.
I've searched so many sites but all they say is about passing the text of the value, but not the text of the name.
Upvotes: 2
Views: 2162
Reputation: 3414
There is no attribute name in <option>
tag
My Code:
<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>
If you are sure want to name field is must there please use getAttribue("name")
instead of text
Code:
alert(select1.options[select1.selectedIndex].getAttribute("name"));
Want to get inner data of the <option>
tag
Code:
alert(select1.options[select1.selectedIndex].text);
Upvotes: 2
Reputation: 1539
You pass the name-Attributes in a separate function with AJAX. All you have to do is to add an ID-Attribute (e.g. "select1") to the select Tag and read out the "textContent" attribute (Fruits in capital letters) of the selected option. Then pass the function "sendToServer" to the "onchange" event of the select-tag.
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>
I know, its not exactly what you asked for, but maybe it helps.
Upvotes: 1