简体   繁体   English

选择非空的第一个选项

[英]Select first option that is not empty

Does anyone know how to autoselect in a selectbox ? 有谁知道如何autoselect一个selectbox I want to do is even though there is a blank option the selectbox will still show the option that has a value on it. 我想要做的是即使有一个blank option框仍然会显示有值的选项。

Does anyone know how to do it in jquery? 有谁知道如何在jquery中做到这一点?

html code: HTML代码:

<select name="name">
<option></option>
<option>Mark</option>
</select>

<select name="age">
<option></option>
<option>16</option>
</select>

May this help you : 愿这可以帮到你:

HTML: HTML:

<select name="name">
<option></option>
<option>Mark</option>
</select>

<select name="age" id='some'>
<option></option>
<option>16</option>
</select>

Jquery: jQuery的:

$($('#some').children()[1]).attr('selected',true)

If you have more than one empty option , and there is no order, this is the best solution I think: 如果您有多个空option ,并且没有订单,这是我认为的最佳解决方案:

jsFiddle Live Demo jsFiddle现场演示

What we've done here is, checking every selectbox by a each loop: 我们在这里做的是,通过每个循环检查每个选择selectbox

 $('select').each(function()
 {

 });

And then inside the loop we find the first option which is not empty : 然后在循环内部我们找到一个 不为空的选项:

$(this).find('option:not(:empty)').first()

And make it selected by prop : 并通过道具选择它:

$(this).find('option:not(:empty)').first().prop('selected',true);

So the whole jQuery and Html will be: 所以整个jQuery和Html将是:

jQuery jQuery的

  $('select').each(function()
  {
        $(this).find('option:not(:empty)').first().prop('selected',true);
  });

HTML HTML

<select name="name">
    <option></option>
    <option>Mark</option>
</select>
<select name="age">
    <option></option>
    <option>16</option>
    <option>20</option>
    <option></option>
    <option>55</option>
    <option></option>
</select>

No need for javascript to do this, if you want to select (Mark) for example, do it like this 如果您想选择(标记),例如,请执行此操作,无需使用javascript执行此操作

<select name="name">
<option></option>
<option selected>Mark</option>
</select>

and in XHTML: 在XHTML中:

<select name="name">
<option></option>
<option selected="selected">Mark</option>
</select>

If you want to do this to all select boxes on the page, use this: 如果要对页面上的所有select框执行此操作,请使用以下命令:

$(function () {
    $('select').each(function () {
        $(this).find('option').not(':empty()').first().attr('selected', true);
    })
});

It grabs each select , finds the first option that is not empty (read: has text inside it) and sets the selected attribute . 它抓取每个select ,找到 第一个 option (读取:其中包含文本)并设置selected属性

See the fiddle . 小提琴

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

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