按选定值获取选择元素

时间:2022-02-23 20:34:06

I'm looking for a way to get a select element using it's selected value. It's easy for options : $('option[value="lol"]');

我正在寻找一种方法来使用它的选定值来获取选择元素。选项很简单:$('option [value =“lol”]');

But it's not working with $('select[value="lol"]');

但它不能用$('select [value =“lol”]');

Is it possible to do this with a simple selector ?

是否可以使用简单的选择器执行此操作?

2 个解决方案

#1


1  

You could use a filter?

你可以使用过滤器吗?

$("select").filter(function() {
    return $(this).val() === "lol";
});

jsFiddle Example

jsFiddle示例

This is assuming you want all <select> elements where the lol option is actually selected. If you just wanted to check to see if the select contains the lol option, selected or not, you can use parent:

这假设您需要所有

$('option[value="lol"]').parent();

jsFiddle Example

jsFiddle示例

#2


0  

You could use something like this in jQuery:

你可以在jQuery中使用这样的东西:

var lol = getSelect(1);

lol.css({
  "color": "red"
});


function getSelect(i) {
  var option = $('select option[value="' + i + '"]');
  return option.parent('select');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="myselect">
    <option value="1">Mr</option>
    <option value="2">Mrs</option>
    <option value="3">Ms</option>
    <option value="4">Dr</option>
    <option value="5">Prof</option>
</select>

#1


1  

You could use a filter?

你可以使用过滤器吗?

$("select").filter(function() {
    return $(this).val() === "lol";
});

jsFiddle Example

jsFiddle示例

This is assuming you want all <select> elements where the lol option is actually selected. If you just wanted to check to see if the select contains the lol option, selected or not, you can use parent:

这假设您需要所有

$('option[value="lol"]').parent();

jsFiddle Example

jsFiddle示例

#2


0  

You could use something like this in jQuery:

你可以在jQuery中使用这样的东西:

var lol = getSelect(1);

lol.css({
  "color": "red"
});


function getSelect(i) {
  var option = $('select option[value="' + i + '"]');
  return option.parent('select');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="myselect">
    <option value="1">Mr</option>
    <option value="2">Mrs</option>
    <option value="3">Ms</option>
    <option value="4">Dr</option>
    <option value="5">Prof</option>
</select>