[英]How to pass html option text as a value for select tag into php $_post using JQuery
I have this following select tag where its option tags are dynamically generated by php: 我有以下选择标记,其中它的选项标记是由php动态生成的:
<select class="form-control " name="list" id="list" onchange="" >
<!-- option tags are dynamically generated-->
</select>
these are some sample options that will be dynamically generated: 以下是一些将动态生成的示例选项:
<option value="1">Item-1</option>
<option value="2">Item-2</option>
<option value="3">Item-3</option>
When i use var_dump($_POST)
i got array (size=1) 'list' => string '1'
for selecting option Item-1
.But i want to pass option text like 'list' => string 'Item-1'
to $_POST
.Also i need the original option value.i try this ajax but didn't work: 当我使用var_dump($_POST)
我得到了array (size=1) 'list' => string '1'
用于选择选项Item-1
。但是我想传递诸如'list' => string 'Item-1'
这样'list' => string 'Item-1'
选项文本'list' => string 'Item-1'
到$_POST
。此外,我需要原始选项值。我尝试使用此Ajax但不起作用:
$("#list").val(this.options[this.selectedIndex].text);
So what ajax i need to do it in correct way.Thanks 所以我需要以正确的方式来做ajax。谢谢
You can simply set the option value to the text you want to recieve: 您可以简单地将选项值设置为要接收的文本:
<option value="Item-1">Item-1</option>
<option value="Item-2">Item-2</option>
<option value="Item-3">Item-3</option>
Or you can get the option text and value like this: 或者,您可以获取选项文本和值,如下所示:
var optionText = $("#list option:selected").text();
var optionValue = $("#list").val();
and later send it to the server via jQuery.ajax()
request: 然后通过jQuery.ajax()
请求将其发送到服务器:
$.ajax({
method: "POST",
url: "yourFile.php",
data: { text: optionText , val: optionValue }
})
.done(function( result ) {
// handle the result
});
In the yourFile.php
you'll have this $_POST
data: 在yourFile.php
您将获得以下$_POST
数据:
array(
'text' => 'selected option text',
'val' => 'selected option value',
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.