简体   繁体   English

检查是否使用jQuery选择了选项,如果没有选择默认值

[英]Check if option is selected with jQuery, if not select a default

Using jQuery, how do you check if there is an option selected in a select menu, and if not, assign one of the options as selected. 使用jQuery,如何检查在选择菜单中是否选择了选项,如果没有,则将其中一个选项指定为选中。

(The select is generated with a maze of PHP functions in an app I just inherited, so this is a quick fix while I get my head around those :) (选择是在我刚刚继承的应用程序中使用迷宫般的PHP函数生成的,所以这是一个快速解决方案,而我可以解决这些问题:)

While I'm not sure about exactly what you want to accomplish, this bit of code worked for me. 虽然我不确定你想要完成什么,但这段代码对我有用。

<select id="mySelect" multiple="multiple">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
  <option value="4">Fourth</option>
</select>

<script type="text/javascript"> 
$(document).ready(function() {
  if (!$("#mySelect option:selected").length) {
    $("#mySelect option[value='3']").attr('selected', 'selected');
  }
});
</script>

No need to use jQuery for this: 不需要为此使用jQuery:

var foo = document.getElementById('yourSelect');
if (foo)
{
   if (foo.selectedIndex != null)
   {
       foo.selectedIndex = 0;
   } 
}

This question is old and has a lot of views, so I'll just throw some stuff out there that will help some people I'm sure. 这个问题已经很久了,并且有很多观点,所以我只想把一些东西放在那里,这将有助于一些我确定的人。

To check if a select element has any selected items: 要检查select元素是否包含任何选定项:

if ($('#mySelect option:selected').length > 0) { alert('has a selected item'); }

or to check if a select has nothing selected: 或检查选择是否没有选择:

if ($('#mySelect option:selected').length == 0) { alert('nothing selected'); }

or if you're in a loop of some sort and want to check if the current element is selected: 或者如果您处于某种循环中并想要检查当前元素是否被选中:

$('#mySelect option').each(function() {
    if ($(this).is(':selected')) { .. }
});

to check if an element is not selected while in a loop: 检查循环中是否未选择元素:

$('#mySelect option').each(function() {
    if ($(this).not(':selected')) { .. }
});

These are some of the ways to do this. 这些是实现此目的的一些方法。 jQuery has many different ways of accomplishing the same thing, so you usually just choose which one appears to be the most efficient. jQuery有许多不同的方法来完成同样的事情,所以你通常只选择哪一个看起来效率最高。

lencioni's answer is what I'd recommend. lencioni的回答是我推荐的。 You can change the selector for the option ('#mySelect option:last') to select the option with a specific value using " #mySelect option[value='yourDefaultValue'] ". 您可以更改选项的选择器('#mySelect option:last') ,使用“ #mySelect option[value='yourDefaultValue'] ”选择具有特定值的#mySelect option[value='yourDefaultValue'] More on selectors . 更多选择器

If you're working extensively with select lists on the client check out this plugin: http://www.texotela.co.uk/code/jquery/select/ . 如果您正在广泛使用客户端上的选择列表,请查看此插件: http//www.texotela.co.uk/code/jquery/select/ Take a look the source if you want to see some more examples of working with select lists. 如果您想查看更多使用选择列表的示例,请查看源代码。

Here is my function changing the selected option. 这是我改变所选选项的功能。 It works for jQuery 1.3.2 它适用于jQuery 1.3.2

function selectOption(select_id, option_val) {
    $('#'+select_id+' option:selected').removeAttr('selected');
    $('#'+select_id+' option[value='+option_val+']').attr('selected','selected');   
}
<script type="text/javascript"> 
$(document).ready(function() {
  if (!$("#mySelect option:selected").length)
   $("#mySelect").val( 3 );

});
</script>

I already came across the texotela plugin mentioned, which let me solve it like this: 我已经看到了提到的texotela插件 ,让我这样解决:

$(document).ready(function(){
    if ( $("#context").selectedValues() == false) {
    $("#context").selectOptions("71");
    }
});

Easy! 简单! The default should be the first option. 默认值应该是第一个选项。 Done! 完成! That would lead you to unobtrusive JavaScript, because JavaScript isn't needed :) 这将导致你不引人注目的JavaScript,因为不需要JavaScript :)

Unobtrusive JavaScript 不引人注目的JavaScript

Look at the selectedIndex of the select element. 查看select元素的selectedIndex BTW, that's a plain ol' DOM thing, not JQuery-specific. 顺便说一下,这是一个简单的'DOM',而不是特定于JQuery的东西。

这是一个我发现有效的快速脚本...... .Result被分配给一个标签。

$(".Result").html($("option:selected").text());
if (!$("#select").find("option:selected").length){
  //
}

You guys are doing way too much for selecting. 你们为选择做得太多了。 Just select by value: 只需按值选择:

$("#mySelect").val( 3 );

I found a good way to check, if option is selected and select a default when it isn't. 如果选择了选项,我找到了一种检查的好方法,如果没有,则选择默认值。

    if(!$('#some_select option[selected="selected"]').val()) {
        //here code if it HAS NOT selected value
        //for exaple adding the first value as "placeholder"
        $('#some_select option:first-child').before('<option disabled selected>Wybierz:</option>');
    }

If #some_select has't default selected option then .val() is undefined 如果#some_select没有默认选择选项,则.val() 未定义

Change event on the select box to fire and once it does then just pull the id attribute of the selected option :- 更改选择框上的事件以触发,然后一旦它执行,只需拉出所选选项的id属性: -

$("#type").change(function(){
  var id = $(this).find("option:selected").attr("id");

  switch (id){
    case "trade_buy_max":
      // do something here
      break;
  }
});

I was just looking for something similar and found this: 我只是在找类似的东西,发现了这个:

$('.mySelect:not(:has(option[selected])) option[value="2"]').attr('selected', true);

This finds all select menus in the class that don't already have an option selected, and selects the default option ("2" in this case). 这将查找类中尚未选择选项的所有选择菜单,并选择默认选项(在本例中为“2”)。

I tried using :selected instead of [selected] , but that didn't work because something is always selected, even if nothing has the attribute 我尝试使用:selected而不是[selected] ,但这不起作用,因为总是选择某些东西,即使没有任何属性

If you need to explicitly check each option to see if any have the "selected" attribute you can do this. 如果您需要明确检查每个选项以查看是否有“选定”属性,您可以执行此操作。 Otherwise using option:selected you'll get the value for the first default option. 否则使用option:selected您将获得第一个默认选项的值。

var viewport_selected = false;      
$('#viewport option').each(function() {
    if ($(this).attr("selected") == "selected") {
        viewport_selected = true;
    }
});
$("option[value*='2']").attr('selected', 'selected');
// 2 for example, add * for every option
$("#select_box_id").children()[1].selected

This is another way of checking an option is selected or not in jquery. 这是在jquery中选择或不选择检查选项的另一种方法。 This will return Boolean (True or False). 这将返回布尔值(True或False)。

[1] is index of select box option [1]是选择框选项的索引

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM