[英]How to get options text in select dropdown in jquery
Here, I need to get options text from the select dropdown and do some operations. 在这里,我需要从选择下拉列表中获取选项文本并执行一些操作。 But, I don't know where I missed.
但是,我不知道我错过了什么。 I am getting both the options text.
我得到两个选项文本。 Here what I tried.
这是我尝试过的。
$('#sel').change(function(){ alert($(this).val()); temp = $('#sel option:selected').text(); alert("temp value " +temp); if(temp = "Option 1") { alert("Option 1 is selected"); //DO SOME OPERATIONS } if(temp = "Option 2") { alert("Option 2 is selected"); //DO SOME OPERATIONS } }).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select name="sel" id="sel"> <option value="1">Option 1</option> <option value="2">Option 2</option <option value="3">Option 3</option </select>
You are missing >
in two places: 您在两个地方缺少
>
:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="sel" id="sel">
<option value="1">Option 1</option>
<option value="2">Option 2</option> <!-- here -->
<option value="3">Option 3</option> <!--and here -->
</select>
You have used assignment operator. 您已经使用了赋值运算符。 It should be
==
instead of =
. 应该是
==
而不是=
。
if (temp == "Option 1") {
alert("Option 1 is selected");
}
if (temp == "Option 2") {
alert("Option 2 is selected");
}
Try like this - 尝试这样-
Html - HTML-
<select id='job_title'>
<option value='' class='job' role=''>- Select -</option>
<option value='1' class='job1' role='Accountant'>Accountant</option>
<option value='2' class='job2' role='Dev. Support'>Dev. Support</option>
</select>
<br />
<input type='text' id='catch_value'>
jQuery - jQuery-
$('#job_title').live('change', function(){
var m = (this.value);
var n = $('.job'+m).attr('role');
$('#catch_value').val(n);
return false;
});
Eg. 例如。 - Fiddle Link
- 小提琴链接
temp = "Option 1" is mistaken expression temp =“选项1”是错误的表达式
temp == "Option 1" or temp === "Option 1" is correct expression temp ==“ Option 1”或temp ===“ Option 1”是正确的表达式
See below 见下文
$('#sel').change(function(){
alert($(this).val());
temp = $('#sel option:selected').text();
alert("temp value " +temp);
if(temp === "Option 1")
{
alert("Option 1 is selected");
//DO SOME OPERATIONS
}
if(temp === "Option 2")
{
alert("Option 2 is selected");
//DO SOME OPERATIONS
}
}).change();
$('#sel').change(function(){
var temp = this[this.selectedIndex].innerHTML;
if(temp == "Option 1") {
alert("Option 1 is selected");
}
if(temp == "Option 2") {
alert("Option 2 is selected");
}
if(temp == "Option 3") {
alert("Option 3 is selected");
}
});
Also add this <option selected disabled>Options:</option>
to your select box in order to have all options available for the event. 还要将此
<option selected disabled>Options:</option>
到选择框中,以使该事件的所有选项可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.