简体   繁体   English

如何使用jQuery在选择框中预选选项

[英]How to preselect option in select box using jQuery

I have one select box with various options. 我有一个选择框有各种选项。

When a page loads then one option with a value, for example 10, should be preselected with jQuery. 当页面加载时,应该使用jQuery预先选择一个带有值的选项,例如10。

How can I do that? 我怎样才能做到这一点?

当页面加载运行时(你可以把它放在<body onload="//put code here"> ):

$("option[value='10']").attr('selected','selected');

Test the example: http://jsfiddle.net/VArCZ/ 测试示例: http //jsfiddle.net/VArCZ/

$(document).ready(function() {

    $('#mySelectBox').val('10');

});

Although, jQuery wouldn't be required for this if the intial value will be static: 虽然,如果初始值是静态的,则不需要jQuery:

<select id='mySelectBox'>
    <option value='5'>5</option>
    <option value='10' selected='selected'>10</option>
    <option value='15'>15</option>
</select>​

上面的代码工作正常,您可以使用以下代码:

$("option[value='10']").attr('selected','selected');

This is something I re-use in my code. 这是我在我的代码中重用的东西。 Hope it be of help. 希望它有所帮助。 You can enable the console output to see whats happening. 您可以启用控制台输出以查看发生的情况。 With this function you can either match the desired option based on the option value or option text as shown in the example below. 使用此功能,您可以根据选项值或选项文本匹配所需选项,如下例所示。

The Html: Html:

<select id="languages">
 <option value="01">JAVA</option>
 <option value="02">HTML</option>
</select>

<select class="data-interchange">
 <option value="A">JSON</option>
 <option value="B">XML</option>
</select>

The JavaScript (Using Jquery) JavaScript(使用Jquery)

$(function() {
  preSelectDropDownList("#languages", "val", "02");
  preSelectDropDownList(".data-interchange", "text", "XML");

  function preSelectDropDownList(selector, checkAgaints, neddle) {
    //console.log(selector, checkAgaints, neddle);//DEBUG
    let hayStack = "";
    neddle = neddle == null ? "" : neddle;
    $(selector + " option").filter(function() {
        if (checkAgaints === "text") {
            hayStack = $(this).text();
        } else if (checkAgaints === "val") {
            hayStack = $(this).val();
        } else {
            alert("Error on Param 2.Only text or value allowed -->" + checkAgaints);
        }
        var result = hayStack.includes(neddle);
        //console.log(neddle+" vs "+hayStack+" = "+result);//DEBUG
        //console.log("Selected return", result);//DEBUG
        return result;
    }).prop('selected', true);
}
});

在最新的jQuery版本中,这对我有用:

$("option[value='10']").prop('selected',true);

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

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