Select2是基于jQuery的选择框的替代品。它支持搜索,远程数据集和无限滚动结果。
我的应用程序使用 select2 显示通过 Ajax 调用检索的姓名列表。 它使用 select2 ajax 功能。 但问题是每当我在 s 上输入时 select2 都会获取项目...
搜索时选择2下拉菜单检查任何字符的出现,需要更改为仅检查第一个字符
我有一个 select2 下拉列表,如下所示: 我需要改变它的搜索方法: 我在下拉列表中有以下值: 苹果 我有一个select2下拉菜单,如下所示: 我需要改变它的搜索方法: 我在下拉列表中有以下值: <option value="1">Apple</option> <option value="2">Orange 2</option> <option value="3">Banana</option> <option value="4">Mango</option> <option value="5">Pomegranate</option> 当我搜索 Mango 时,它显示 Mango 和 Pomegranate,因为两者都包含字母 M。 我只需要按第一个字符搜索,就像当我用字母M搜索时,它应该只给出Mango,而不应该检查中间的字符!! 检查我的小提琴:FIDDLE 您可以创建一个自定义匹配器。 如文档中所写: 自定义匹配器使用仅捆绑在 Select2 完整版本中的兼容性模块。您还可以选择使用更复杂的匹配器。 编辑 在这里你可以找到一个实现你需要的代码的小提琴。 这是官方文档参考 $(document).ready(function () { // Single select example if using params obj or configuration seen above var configParamsObj = { placeholder: 'Select an option...', // Place holder text to place in the select minimumResultsForSearch: 3, // Overrides default of 15 set above matcher: function (params, data) { // If there are no search terms, return all of the data if ($.trim(params.term) === '') { return data; } // `params.term` should be the term that is used for searching // `data.text` is the text that is displayed for the data object if (data.text.toLowerCase().startsWith(params.term.toLowerCase())) { var modifiedData = $.extend({}, data, true); modifiedData.text += ' (matched)'; // You can return modified objects from here // This includes matching the `children` how you want in nested data sets return modifiedData; } // Return `null` if the term should not be displayed return null; } }; $("#singleSelectExample").select2(configParamsObj); }); .selectRow { display : block; padding : 20px; } .select2-container { width: 200px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" /> <script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script> <body>Single select example <div class="selectRow"> <select id="singleSelectExample"> <option></option> <option value="1">Apple</option> <option value="2">Orange 2</option> <option value="3">Banana</option> <option value="4">Mango</option> <option value="5">Pomegranate</option> </select> </div> </body>
我下载了 Select2 jquery 插件并完成了所有设置 - 我这里有一个基本的下拉菜单。 男 我下载了 Select2 jquery 插件并进行了全部设置 - 我这里有一个基本的下拉菜单。 <SELECT NAME="GENDER"> <OPTION VALUE="1">MALE <OPTION VALUE="2">FEMALE <OPTION VALUE="3">UNDEFINED </SELECT> 我应用了该插件并且它可以工作 - 不是问题。 我一直在查看 select2 文档,我想做的不是按性别搜索,例如输入女性和男性等 - 我希望用户只需按 1,这样它就会显示男性,2 代表女性。 有人在 select2 中尝试过这个吗? 查看文档中的“匹配器”选项:http://ivaynberg.github.io/select2/#documentation 重写匹配器函数以检查给定选项的 text() 和 val()。未经测试的示例: $('select').select2({ matcher: function(term, text, option) { return text.toUpperCase().indexOf(term.toUpperCase())>=0 || option.val().toUpperCase().indexOf(term.toUpperCase())>=0; } }); 自从回答此问题后,“匹配器”选项的参数已更改。我在实现美国州下拉列表时遇到了同样的问题,每个选项都像<option value="PA">Pennsylvania</option>,我希望用户能够拼写州或简单地键入他们的代码并且它可以工作。根据更新的文档,我修改如下: $('select').select2({ matcher: function(params, data) { // If there are no search terms, return all of the data if ($.trim(params.term) === '') { return data; } // Do not display the item if there is no 'text' property if (typeof data.text === 'undefined') { return null; } // `params.term` is the user's search term // `data.id` should be checked against // `data.text` should be checked against var q = params.term.toLowerCase(); if (data.text.toLowerCase().indexOf(q) > -1 || data.id.toLowerCase().indexOf(q) > -1) { return $.extend({}, data, true); } // Return `null` if the term should not be displayed return null; } }); 这是我制作的一个工作 CodePen 演示,它使用 OP 的选择字段和美国各州的选择字段来演示这一点。 我采纳了@Tessa上面的精彩答案,并使其与optGroup一起工作。 function(params, option) { // If there are no search terms, return all of the option var searchTerm = $.trim(params.term); if (searchTerm === '') { return option; } // Do not display the item if there is no 'text' property if (typeof option.text === 'undefined') { return null; } var searchTermLower = searchTerm.toLowerCase(); // `params.term` is the user's search term // `option.id` should be checked against // `option.text` should be checked against var searchFunction = function(thisOption, searchTerm) { return thisOption.text.toLowerCase().indexOf(searchTerm) > -1 || (thisOption.id && thisOption.id.toLowerCase().indexOf(searchTerm) > -1); }; if (!option.children) { //we only need to check this option return searchFunction(option, searchTermLower) ? option : null; } //need to search all the children option.children = option .children .filter(function (childOption) { return searchFunction(childOption, searchTermLower); }); return option; } $('select').select2({ matcher: function(params, data) { // Do not display the item if there is no 'text' property if (typeof data.text === 'undefined') { return null; } // If there are no search terms, return all of the data if (params.term === '' || typeof params.term === 'undefined') { return data; } else { // `params.term` is the user's search term // `data.id` should be checked against // `data.text` should be checked against // console.log(params.term.toLowerCase()); var q = params.term.toLowerCase(); if (data.text.toLowerCase().indexOf(q) > -1 || data.id.toLowerCase().indexOf(q) > -1) { return $.extend({}, data, true); } } // Return `null` if the term should not be displayed return null; } });
我在我的 asp.net mvc 5 应用程序中使用 Select2 插件。根据文档 如果您需要更多,占位符选项允许您传入数据对象而不仅仅是字符串
我想在我的选项中选择复选框,但不知道该怎么做。 参考 这是我的选择框代码: 我想在我的选项中选择复选框,但不知道该怎么做。 参考文献 这是我的选择框代码: <select class="form-control select2" id="data-set" name="data[]" multiple="multiple"> @foreach($data as $row) <option value="{{ $row->name }}">{{ $row->name }}</option> @endforeach </select> JS代码: $('#lawFirms').select2({ placeholder: "Select options", allowClear: true }); 我建议查看其他线程,其中还有其他一些可能对您有帮助的好答案。
我有一个模态,该模态使用js动态显示内容。模态 html 是这样的: 我有一个模态,该模态通过使用 js 动态显示内容。模态 html 是这样的: <button type="button" class="openModalBtn btn btn-outline btn-primary btn-sm mb-1" data-template="templateModalEducation" data-title="Education"> <i class="fas fa-plus"></i> Add </button> <div id="modal" draggable="true" class="modal fade bd-example-modal-lg hide" role="dialog"> <div class="modal-dialog modal-dialog-centered modal-lg"> <div class="modal-content"> <div class="modal-header" style="margin-bottom: 10px;"> <b class="modal-title" id="modalTitle">Modal Title</b> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div id="modalBody" class="modal-body pt-0"> @* Modal content will be injected here *@ </div> </div> </div> </div> 然后模态使用我提供的模板将内容附加到“modalBody”内。内容正文模板的一个示例是: <div id="templateModalEducation"> <div class="row"> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label class="Requiredinput">Year</label> <input type="text" class="form-control edu-year"> <span id="edu-year-validation" class="text-validation"></span> </div> </div> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label class="Requiredinput">Level</label> <select class="form-control select2normalWithouClear edu-level" data-placeholder="Select Education Level"> <option></option> @if (Model.EduLevelDropdownList != null) { foreach (var level in Model.EduLevelDropdownList) { <option>@level.CodeName</option> } } </select> <span id="edu-level-validation" class="text-validation"></span> </div> </div> </div> <div class="row"> <div class="col-md-12 col-sm-12"> <div class="form-group"> <label class="Requiredinput">Institution Name</label> <select class="form-control select2normalWithouClear edu-instituteName" data-placeholder="Select Institution Name"> <option></option> <option value="0">Other</option> @if (Model.EduInstitutionDropdownList != null) { foreach (var institute in Model.EduInstitutionDropdownList) { <option>@institute.CodeName</option> } } </select> <span id="edu-instituteName-validation" class="text-validation"></span> </div> <div class="form-group"> <input type="text" class="form-control edu-instituteNameOther"> </div> <span id="edu-instituteNameOther-validation" class="text-validation"></span> </div> </div> <div class="modal-footer d-flex justify-content-end m-0 p-0"> <button id="addEducationRowToMainForm" data-target-table="#tableEducation" type="button" class="btn btn-outline btn-primary btn-sm mb-1"> <i class="fas fa-plus"></i> Add </button> <button id="updateEducationRow" type="button" class="btn btn-outline btn-primary btn-sm mb-1" style="display: none;"> <i class="fas fa-save"></i> Update </button> </div> </div> 这是我的 JavaScript 代码,它动态更改模式的内容: <script> // Function to load different template content into the modal function loadModalContent(templateId, title) { // Clear previous content to prevent duplication $('#modalBody').empty(); $('#modalBody .select2normalWithouClear').select2('destroy'); // Load new content and set the title var templateContent = $('#' + templateId).html(); // Get the content of the template $('#modalBody').html(templateContent); // Inject content into the modal body $('#modalTitle').text(title); // Set the modal title $('#modalBody .select2normalWithouClear').select2({ placeholder: $(this).data('placeholder') }); $('.edu-instituteNameOther').hide(); $('#modal').modal('show'); // Show the modal } // Event listener for buttons that trigger the modal with different templates $(document).on('click', '.openModalBtn', function () { var templateId = $(this).data('template'); // Get the template to load var modalTitle = $(this).data('title'); // Get the title for the modal loadModalContent(templateId, modalTitle); // Call the function to load the content TMCEWoFileUpl("250", ""); }); </script> 问题是,当我在页面加载后打开模式时,它会显示两个下拉菜单:一个功能正常,而另一个似乎是重复的并且不起作用。但是,当我第二次打开模式时,下拉列表会正确显示并且不会重复。有人可以帮我解决这个问题吗? 我尝试过在模态之外初始化它,但仍然不起作用。 这是现场演示: // Function to load different template content into the modal function loadModalContent(templateId, title) { // Clear previous content to prevent duplication $('#modalBody').empty(); $('#modalBody .select2normalWithouClear').select2('destroy'); // Load new content and set the title var templateContent = $('#' + templateId).html(); // Get the content of the template $('#modalBody').html(templateContent); // Inject content into the modal body $('#modalTitle').text(title); // Set the modal title $('#modalBody .select2normalWithouClear').select2({ placeholder: $(this).data('placeholder') }); $('.edu-instituteNameOther').hide(); $('#modal').modal('show'); // Show the modal } // Event listener for buttons that trigger the modal with different templates $(document).on('click', '.openModalBtn', function() { var templateId = $(this).data('template'); // Get the template to load var modalTitle = $(this).data('title'); // Get the title for the modal loadModalContent(templateId, modalTitle); // Call the function to load the content //TMCEWoFileUpl("250", ""); }); <link href="~/lib/jquery-ui-1.13.2/jquery-ui.min.css" rel="stylesheet" /> <script src="~/lib/jquery-ui-1.13.2/jquery-ui.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" integrity="sha512-jnSuA4Ss2PkkikSOLtYs8BlYIeeIK1h99ty4YfvRPAlzr377vr3CXDb7sb7eEEBYjDtcYj+AjBH3FLv5uSJuXg==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.min.js" integrity="sha512-ykZ1QQr0Jy/4ZkvKuqWn4iF3lqPZyij9iRv6sGqLRdTPkY69YX6+7wvVGmsdBbiIfN/8OdsI7HABjvEok6ZopQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <button type="button" class="openModalBtn btn btn-outline btn-primary btn-sm mb-1" data-template="templateModalEducation" data-title="Education"> <i class="fas fa-plus"></i> Add </button> <div id="modal" draggable="true" class="modal fade bd-example-modal-lg hide" role="dialog"> <div class="modal-dialog modal-dialog-centered modal-lg"> <div class="modal-content"> <div class="modal-header" style="margin-bottom: 10px;"> <b class="modal-title" id="modalTitle">Modal Title</b> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div id="modalBody" class="modal-body pt-0"> @* Modal content will be injected here *@ </div> </div> </div> </div> <hr> <div id="templateModalEducation"> <div class="row"> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label class="Requiredinput">Year</label> <input type="text" class="form-control edu-year"> <span id="edu-year-validation" class="text-validation"></span> </div> </div> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label class="Requiredinput">Level</label> <select class="form-control select2normalWithouClear edu-level" data-placeholder="Select Education Level"> <option></option> <option value="1">Option1</option> <option value="2">Option2</option> <option value="3">Option3</option> <!-- @if (Model.EduLevelDropdownList != null) { foreach (var level in Model.EduLevelDropdownList) { <option>@level.CodeName</option> } } --> </select> <span id="edu-level-validation" class="text-validation"></span> </div> </div> </div> <div class="row"> <div class="col-md-12 col-sm-12"> <div class="form-group"> <label class="Requiredinput">Institution Name</label> <select class="form-control select2normalWithouClear edu-instituteName" data-placeholder="Select Institution Name" > <option></option> <option value="0">Other</option> <option value="1">Option1</option> <option value="2">Option2</option> <option value="3">Option3</option> <!-- @if (Model.EduInstitutionDropdownList != null) { foreach (var institute in Model.EduInstitutionDropdownList) { <option>@institute.CodeName</option> } } --> </select> <span id="edu-instituteName-validation" class="text-validation"></span> </div> <div class="form-group"> <input type="text" class="form-control edu-instituteNameOther"> </div> <span id="edu-instituteNameOther-validation" class="text-validation"></span> </div> </div> <div class="modal-footer d-flex justify-content-end m-0 p-0"> <button id="addEducationRowToMainForm" data-target-table="#tableEducation" type="button" class="btn btn-outline btn-primary btn-sm mb-1" > <i class="fas fa-plus"></i> Add </button> <button id="updateEducationRow" type="button" class="btn btn-outline btn-primary btn-sm mb-1" style="display: none;" > <i class="fas fa-save"></i> Update </button> </div> </div> 我根据 aurelian-scarlat 在 此 GitHub 问题中的评论找到了解决方案 如果你的盒子有一个名为 select2 的类,你会遇到麻烦,因为还有一些其他元素具有相同的类。 所以这是错误的:$('.select2').select2('destroy'); 正确的做法是: $('select.select2').select2('destroy'); 或者更改盒子的类别:$('.select-select2').select2('destroy'); 或者更好的是,使用 id:$('#selectbox').select2('destroy'); 我花了一段时间才弄清楚这一点,我希望它对某人有帮助。 我不能使用类名.select2normalWithouClear,因为还有一些其他元素具有相同的类。所以我所做的就是为我的所有选择赋予相同的新类名称,并像这样初始化它们: <select class="form-control select2normalWithouClear edu-level mySelectDropdown" data-placeholder="Select Education Level"><option>Test 1</option><option>Test 2</option><option>Test 3</option></select> <select class="form-control select2normalWithouClear edu-instituteName mySelectDropdown" data-placeholder="Select Institution Name"><option>Test 1</option><option>Test 2</option><option>Test 3</option></select> 初始化它: $('.mySelectDropdown').select2({ placeholder: $(this).data('placeholder') });
我有一个模态,该模态使用js动态显示内容。模态 html 是这样的: 我有一个模态,该模态通过使用 js 动态显示内容。模态 html 是这样的: <button type="button" class="openModalBtn btn btn-outline btn-primary btn-sm mb-1" data-template="templateModalEducation" data-title="Education"> <i class="fas fa-plus"></i> Add </button> <div id="modal" draggable="true" class="modal fade bd-example-modal-lg hide" role="dialog"> <div class="modal-dialog modal-dialog-centered modal-lg"> <div class="modal-content"> <div class="modal-header" style="margin-bottom: 10px;"> <b class="modal-title" id="modalTitle">Modal Title</b> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div id="modalBody" class="modal-body pt-0"> @* Modal content will be injected here *@ </div> </div> </div> </div> 然后模态使用我提供的模板将内容附加到“modalBody”内。内容正文模板的一个示例是: <div id="templateModalEducation"> <div class="row"> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label class="Requiredinput">Year</label> <input type="text" class="form-control edu-year"> <span id="edu-year-validation" class="text-validation"></span> </div> </div> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label class="Requiredinput">Level</label> <select class="form-control select2normalWithouClear edu-level" data-placeholder="Select Education Level"> <option></option> @if (Model.EduLevelDropdownList != null) { foreach (var level in Model.EduLevelDropdownList) { <option>@level.CodeName</option> } } </select> <span id="edu-level-validation" class="text-validation"></span> </div> </div> </div> <div class="row"> <div class="col-md-12 col-sm-12"> <div class="form-group"> <label class="Requiredinput">Institution Name</label> <select class="form-control select2normalWithouClear edu-instituteName" data-placeholder="Select Institution Name"> <option></option> <option value="0">Other</option> @if (Model.EduInstitutionDropdownList != null) { foreach (var institute in Model.EduInstitutionDropdownList) { <option>@institute.CodeName</option> } } </select> <span id="edu-instituteName-validation" class="text-validation"></span> </div> <div class="form-group"> <input type="text" class="form-control edu-instituteNameOther"> </div> <span id="edu-instituteNameOther-validation" class="text-validation"></span> </div> </div> <div class="modal-footer d-flex justify-content-end m-0 p-0"> <button id="addEducationRowToMainForm" data-target-table="#tableEducation" type="button" class="btn btn-outline btn-primary btn-sm mb-1"> <i class="fas fa-plus"></i> Add </button> <button id="updateEducationRow" type="button" class="btn btn-outline btn-primary btn-sm mb-1" style="display: none;"> <i class="fas fa-save"></i> Update </button> </div> </div> 这是我的 JavaScript 代码,它动态更改模式的内容: <script> // Function to load different template content into the modal function loadModalContent(templateId, title) { // Clear previous content to prevent duplication $('#modalBody').empty(); $('#modalBody .select2normalWithouClear').select2('destroy'); // Load new content and set the title var templateContent = $('#' + templateId).html(); // Get the content of the template $('#modalBody').html(templateContent); // Inject content into the modal body $('#modalTitle').text(title); // Set the modal title $('#modalBody .select2normalWithouClear').select2({ placeholder: $(this).data('placeholder') }); $('.edu-instituteNameOther').hide(); $('#modal').modal('show'); // Show the modal } // Event listener for buttons that trigger the modal with different templates $(document).on('click', '.openModalBtn', function () { var templateId = $(this).data('template'); // Get the template to load var modalTitle = $(this).data('title'); // Get the title for the modal loadModalContent(templateId, modalTitle); // Call the function to load the content TMCEWoFileUpl("250", ""); }); </script> 问题是,当我在页面加载后打开模式时,它会显示两个下拉菜单:一个功能正常,而另一个似乎是重复的并且不起作用。但是,当我第二次打开模式时,下拉列表会正确显示并且不会重复。有人可以帮我解决这个问题吗? 我尝试过在模态之外初始化它,但仍然不起作用。 这是现场演示: // Function to load different template content into the modal function loadModalContent(templateId, title) { // Clear previous content to prevent duplication $('#modalBody').empty(); $('#modalBody .select2normalWithouClear').select2('destroy'); // Load new content and set the title var templateContent = $('#' + templateId).html(); // Get the content of the template $('#modalBody').html(templateContent); // Inject content into the modal body $('#modalTitle').text(title); // Set the modal title $('#modalBody .select2normalWithouClear').select2({ placeholder: $(this).data('placeholder') }); $('.edu-instituteNameOther').hide(); $('#modal').modal('show'); // Show the modal } // Event listener for buttons that trigger the modal with different templates $(document).on('click', '.openModalBtn', function() { var templateId = $(this).data('template'); // Get the template to load var modalTitle = $(this).data('title'); // Get the title for the modal loadModalContent(templateId, modalTitle); // Call the function to load the content //TMCEWoFileUpl("250", ""); }); <link href="~/lib/jquery-ui-1.13.2/jquery-ui.min.css" rel="stylesheet" /> <script src="~/lib/jquery-ui-1.13.2/jquery-ui.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" integrity="sha512-jnSuA4Ss2PkkikSOLtYs8BlYIeeIK1h99ty4YfvRPAlzr377vr3CXDb7sb7eEEBYjDtcYj+AjBH3FLv5uSJuXg==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.min.js" integrity="sha512-ykZ1QQr0Jy/4ZkvKuqWn4iF3lqPZyij9iRv6sGqLRdTPkY69YX6+7wvVGmsdBbiIfN/8OdsI7HABjvEok6ZopQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <button type="button" class="openModalBtn btn btn-outline btn-primary btn-sm mb-1" data-template="templateModalEducation" data-title="Education"> <i class="fas fa-plus"></i> Add </button> <div id="modal" draggable="true" class="modal fade bd-example-modal-lg hide" role="dialog"> <div class="modal-dialog modal-dialog-centered modal-lg"> <div class="modal-content"> <div class="modal-header" style="margin-bottom: 10px;"> <b class="modal-title" id="modalTitle">Modal Title</b> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div id="modalBody" class="modal-body pt-0"> @* Modal content will be injected here *@ </div> </div> </div> </div> <hr> <div id="templateModalEducation"> <div class="row"> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label class="Requiredinput">Year</label> <input type="text" class="form-control edu-year"> <span id="edu-year-validation" class="text-validation"></span> </div> </div> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label class="Requiredinput">Level</label> <select class="form-control select2normalWithouClear edu-level" data-placeholder="Select Education Level"> <option></option> <option value="1">Option1</option> <option value="2">Option2</option> <option value="3">Option3</option> <!-- @if (Model.EduLevelDropdownList != null) { foreach (var level in Model.EduLevelDropdownList) { <option>@level.CodeName</option> } } --> </select> <span id="edu-level-validation" class="text-validation"></span> </div> </div> </div> <div class="row"> <div class="col-md-12 col-sm-12"> <div class="form-group"> <label class="Requiredinput">Institution Name</label> <select class="form-control select2normalWithouClear edu-instituteName" data-placeholder="Select Institution Name" > <option></option> <option value="0">Other</option> <option value="1">Option1</option> <option value="2">Option2</option> <option value="3">Option3</option> <!-- @if (Model.EduInstitutionDropdownList != null) { foreach (var institute in Model.EduInstitutionDropdownList) { <option>@institute.CodeName</option> } } --> </select> <span id="edu-instituteName-validation" class="text-validation"></span> </div> <div class="form-group"> <input type="text" class="form-control edu-instituteNameOther"> </div> <span id="edu-instituteNameOther-validation" class="text-validation"></span> </div> </div> <div class="modal-footer d-flex justify-content-end m-0 p-0"> <button id="addEducationRowToMainForm" data-target-table="#tableEducation" type="button" class="btn btn-outline btn-primary btn-sm mb-1" > <i class="fas fa-plus"></i> Add </button> <button id="updateEducationRow" type="button" class="btn btn-outline btn-primary btn-sm mb-1" style="display: none;" > <i class="fas fa-save"></i> Update </button> </div> </div> 如果我的问题不清楚,我很抱歉,我对这个领域还是新手。不过,我根据 GitHub 问题中“aurelian-scarlat”的评论找到了一个解决方案: https://github.com/Meteor-Community-Packages/meteor-autoform-select2/issues/44 我无法使用类名“.select2normalWithouClear”,因为还有一些其他元素具有相同的类。所以我所做的就是为我的所有选择赋予相同的新类名称,并像这样初始化它们: <select class="form-control select2normalWithouClear edu-level mySelectDropdown" data-placeholder="Select Education Level"><option>Test 1</option><option>Test 2</option><option>Test 3</option></select> <select class="form-control select2normalWithouClear edu-instituteName mySelectDropdown" data-placeholder="Select Institution Name"><option>Test 1</option><option>Test 2</option><option>Test 3</option></select> 初始化它: $('.mySelectDropdown').select2({ placeholder: $(this).data('placeholder') });
我有一个模态,该模态使用js动态显示内容。模态 html 是这样的: 我有一个模态,该模态通过使用 js 动态显示内容。模态 html 是这样的: <button type="button" class="openModalBtn btn btn-outline btn-primary btn-sm mb-1" data-template="templateModalEducation" data-title="Education"> <i class="fas fa-plus"></i> Add </button> <div id="modal" draggable="true" class="modal fade bd-example-modal-lg hide" role="dialog"> <div class="modal-dialog modal-dialog-centered modal-lg"> <div class="modal-content"> <div class="modal-header" style="margin-bottom: 10px;"> <b class="modal-title" id="modalTitle">Modal Title</b> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div id="modalBody" class="modal-body pt-0"> @* Modal content will be injected here *@ </div> </div> </div> </div> 然后模态使用我提供的模板将内容附加到“modalBody”内。内容正文模板的一个示例是: <div id="templateModalEducation"> <div class="row"> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label class="Requiredinput">Year</label> <input type="text" class="form-control edu-year"> <span id="edu-year-validation" class="text-validation"></span> </div> </div> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label class="Requiredinput">Level</label> <select class="form-control select2normalWithouClear edu-level" data-placeholder="Select Education Level"> <option></option> @if (Model.EduLevelDropdownList != null) { foreach (var level in Model.EduLevelDropdownList) { <option>@level.CodeName</option> } } </select> <span id="edu-level-validation" class="text-validation"></span> </div> </div> </div> <div class="row"> <div class="col-md-12 col-sm-12"> <div class="form-group"> <label class="Requiredinput">Institution Name</label> <select class="form-control select2normalWithouClear edu-instituteName" data-placeholder="Select Institution Name"> <option></option> <option value="0">Other</option> @if (Model.EduInstitutionDropdownList != null) { foreach (var institute in Model.EduInstitutionDropdownList) { <option>@institute.CodeName</option> } } </select> <span id="edu-instituteName-validation" class="text-validation"></span> </div> <div class="form-group"> <input type="text" class="form-control edu-instituteNameOther"> </div> <span id="edu-instituteNameOther-validation" class="text-validation"></span> </div> </div> <div class="modal-footer d-flex justify-content-end m-0 p-0"> <button id="addEducationRowToMainForm" data-target-table="#tableEducation" type="button" class="btn btn-outline btn-primary btn-sm mb-1"> <i class="fas fa-plus"></i> Add </button> <button id="updateEducationRow" type="button" class="btn btn-outline btn-primary btn-sm mb-1" style="display: none;"> <i class="fas fa-save"></i> Update </button> </div> </div> 这是我的 JavaScript 代码,它动态更改模式的内容: <script> // Function to load different template content into the modal function loadModalContent(templateId, title) { // Clear previous content to prevent duplication $('#modalBody').empty(); $('#modalBody .select2normalWithouClear').select2('destroy'); // Load new content and set the title var templateContent = $('#' + templateId).html(); // Get the content of the template $('#modalBody').html(templateContent); // Inject content into the modal body $('#modalTitle').text(title); // Set the modal title $('#modalBody .select2normalWithouClear').select2({ placeholder: $(this).data('placeholder') }); $('.edu-instituteNameOther').hide(); $('#modal').modal('show'); // Show the modal } // Event listener for buttons that trigger the modal with different templates $(document).on('click', '.openModalBtn', function () { var templateId = $(this).data('template'); // Get the template to load var modalTitle = $(this).data('title'); // Get the title for the modal loadModalContent(templateId, modalTitle); // Call the function to load the content TMCEWoFileUpl("250", ""); }); </script> 问题是,当我在页面加载后打开模式时,它会显示两个下拉菜单:一个功能正常,而另一个似乎是重复的并且不起作用。但是,当我第二次打开模式时,下拉列表会正确显示并且不会重复。有人可以帮我解决这个问题吗? 我尝试过在模态之外初始化它,但仍然不起作用。 这是现场演示: // Function to load different template content into the modal function loadModalContent(templateId, title) { // Clear previous content to prevent duplication $('#modalBody').empty(); $('#modalBody .select2normalWithouClear').select2('destroy'); // Load new content and set the title var templateContent = $('#' + templateId).html(); // Get the content of the template $('#modalBody').html(templateContent); // Inject content into the modal body $('#modalTitle').text(title); // Set the modal title $('#modalBody .select2normalWithouClear').select2({ placeholder: $(this).data('placeholder') }); $('.edu-instituteNameOther').hide(); $('#modal').modal('show'); // Show the modal } // Event listener for buttons that trigger the modal with different templates $(document).on('click', '.openModalBtn', function() { var templateId = $(this).data('template'); // Get the template to load var modalTitle = $(this).data('title'); // Get the title for the modal loadModalContent(templateId, modalTitle); // Call the function to load the content //TMCEWoFileUpl("250", ""); }); <link href="~/lib/jquery-ui-1.13.2/jquery-ui.min.css" rel="stylesheet" /> <script src="~/lib/jquery-ui-1.13.2/jquery-ui.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" integrity="sha512-jnSuA4Ss2PkkikSOLtYs8BlYIeeIK1h99ty4YfvRPAlzr377vr3CXDb7sb7eEEBYjDtcYj+AjBH3FLv5uSJuXg==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.min.js" integrity="sha512-ykZ1QQr0Jy/4ZkvKuqWn4iF3lqPZyij9iRv6sGqLRdTPkY69YX6+7wvVGmsdBbiIfN/8OdsI7HABjvEok6ZopQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <button type="button" class="openModalBtn btn btn-outline btn-primary btn-sm mb-1" data-template="templateModalEducation" data-title="Education"> <i class="fas fa-plus"></i> Add </button> <div id="modal" draggable="true" class="modal fade bd-example-modal-lg hide" role="dialog"> <div class="modal-dialog modal-dialog-centered modal-lg"> <div class="modal-content"> <div class="modal-header" style="margin-bottom: 10px;"> <b class="modal-title" id="modalTitle">Modal Title</b> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div id="modalBody" class="modal-body pt-0"> @* Modal content will be injected here *@ </div> </div> </div> </div> <hr> <div id="templateModalEducation"> <div class="row"> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label class="Requiredinput">Year</label> <input type="text" class="form-control edu-year"> <span id="edu-year-validation" class="text-validation"></span> </div> </div> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label class="Requiredinput">Level</label> <select class="form-control select2normalWithouClear edu-level" data-placeholder="Select Education Level"> <option></option> <option value="1">Option1</option> <option value="2">Option2</option> <option value="3">Option3</option> <!-- @if (Model.EduLevelDropdownList != null) { foreach (var level in Model.EduLevelDropdownList) { <option>@level.CodeName</option> } } --> </select> <span id="edu-level-validation" class="text-validation"></span> </div> </div> </div> <div class="row"> <div class="col-md-12 col-sm-12"> <div class="form-group"> <label class="Requiredinput">Institution Name</label> <select class="form-control select2normalWithouClear edu-instituteName" data-placeholder="Select Institution Name" > <option></option> <option value="0">Other</option> <option value="1">Option1</option> <option value="2">Option2</option> <option value="3">Option3</option> <!-- @if (Model.EduInstitutionDropdownList != null) { foreach (var institute in Model.EduInstitutionDropdownList) { <option>@institute.CodeName</option> } } --> </select> <span id="edu-instituteName-validation" class="text-validation"></span> </div> <div class="form-group"> <input type="text" class="form-control edu-instituteNameOther"> </div> <span id="edu-instituteNameOther-validation" class="text-validation"></span> </div> </div> <div class="modal-footer d-flex justify-content-end m-0 p-0"> <button id="addEducationRowToMainForm" data-target-table="#tableEducation" type="button" class="btn btn-outline btn-primary btn-sm mb-1" > <i class="fas fa-plus"></i> Add </button> <button id="updateEducationRow" type="button" class="btn btn-outline btn-primary btn-sm mb-1" style="display: none;" > <i class="fas fa-save"></i> Update </button> </div> </div> 如果我的问题不清楚,我很抱歉,我对这个领域还是新手。不过,我根据 GitHub 问题中“aurelian-scarlat”的评论找到了一个解决方案: https://github.com/Meteor-Community-Packages/meteor-autoform-select2/issues/44 我无法使用类名“.select2normalWithouClear”,因为还有一些其他元素具有相同的类。所以我所做的就是为我的所有选择赋予相同的新类名称,并像这样初始化它们: <select class="form-control select2normalWithouClear edu-level mySelectDropdown" data-placeholder="Select Education Level"><option>Test 1</option><option>Test 2</option><option>Test 3</option></select> <select class="form-control select2normalWithouClear edu-instituteName mySelectDropdown" data-placeholder="Select Institution Name"><option>Test 1</option><option>Test 2</option><option>Test 3</option></select> 初始化它: $('.mySelectDropdown').select2({ placeholder: $(this).data('placeholder') });
我的清除按钮与占位符重叠: 你有遇到过这个问题吗? 我正在为 select2 使用 bootstrap5 主题。 其他一切都有效。 正是这个按钮导致了问题。 谢谢...
我在 Django 应用程序中使用 Select2 多重选择,并且遇到一个问题,即所选项目被绘制在输入字段之外。你对 CSS 是如何被搞乱导致这种情况有什么想法吗?
我已经能够更改 select2 框的高度并应用一些更改,但我现在的问题是 select2 框中的文本出现在选择框的中心以及顶部......
我正在尝试使用出色的 Select2 库以编程方式清除下拉列表。使用 Select2 查询选项通过远程 ajax 调用动态填充下拉列表。 HTML: 我正在尝试使用出色的 Select2 库以编程方式清除下拉菜单。使用 Select2 query 选项,下拉列表会动态填充远程 ajax 调用。 HTML: <input id="remote" type="hidden" data-placeholder="Choose Something" /> Javascript: var $remote = $('#remote'); $remote.select2({ allowClear: true, minimumInputLength: 2, query: function(options){ $.ajax({ dataType: 'json', url: myURL + options.term, error: function(jqXHR, textStatus, errorThrown){ smoke.alert(textStatus + ": server returned error on parsing arguments starting with " + options.term); }, success: function(data, textStatus, jqXHR){ var results = []; for(var i = 0; i < data.length; ++i){ results.push({id: data[i].id, text: data[i].name}); } options.callback({results: results, more: false}); } }); } }); 不幸的是,对 $remove.select2('val', '') 的调用会抛出以下异常: Uncaught Error: cannot call val() if initSelection() is not defined 我尝试过设置attr、设置val、text和Select2特定的data功能。似乎无法让这个人清楚地以单选按钮的方式工作。有人有建议吗? 这对我有用: $remote.select2('data', {id: null, text: null}) 当您以这种方式清除它时,它也可以与 jQuery 验证一起使用。 -- 编辑2013-04-09 在撰写此回复时,这是唯一的方法。通过最近的补丁,现在可以使用正确且更好的方法。 $remote.select2('data', null) 如果是 Select2 版本 4+ 它改变了语法,你需要这样写: // clear all option $('#select_with_blank_data').html('').select2({data: [{id: '', text: ''}]}); // clear and add new option $("#select_with_data").html('').select2({data: [ {id: '', text: ''}, {id: '1', text: 'Facebook'}, {id: '2', text: 'Youtube'}, {id: '3', text: 'Instagram'}, {id: '4', text: 'Pinterest'}]}); 这是正确的,select2将清除所选值并返回占位符。 $remote.select2('data', null) 对于 select2 版本 4,可以轻松使用这个: $('#remote').empty(); 使用ajax调用填充select元素后,您可能需要在成功部分添加这行代码来更新内容: success: function(data, textStatus, jqXHR){ $('#remote').change(); } 使用 select2 版本 4,您可以使用这个简短的符号: $('#remote').html('').select2({data: {id:null, text: null}}); 这会在创建时将带有 null id 和文本的 json 数组传递给 select2,但首先使用 .html('') 清空之前存储的结果。 你应该使用这个: $('#remote').val(null).trigger("change"); 这解决了我在 3.5.2 版本中的问题。 $remote.empty().append(new Option()).trigger('change'); 根据此问题,您需要在选择标记内有一个空选项才能显示占位符。 提出的方法@Lelio Faieta对我有用,但因为我使用bootstrap主题,它删除了select2的所有引导设置。所以我使用了以下代码: $("#remote option").remove(); 我有点晚了,但这就是上一个版本(4.0.3)中的功能: $('#select_id').val('').trigger('change'); 这些都可以帮助我清除下拉列表: .select2('data', null) .select2('val', null) 但重要提示:值不会被重置,.val() 将返回第一个选项,即使它没有被选择。我正在使用 Select2 3.5.3 我找到了我在另一个问题中寻找的答案(对user780178的赞美): 重置 select2 值并显示占位符 $("#customers_select").select2("val", ""); 从 >4.0 开始,为了真正清理 select2,您需要执行以下操作: $remote.select2.val(''); $remote.select2.html(''); selectedValues = []; // if you have some variable where you store the values $remote.select2.trigger("change"); 请注意,我们根据最初的问题选择 select2。在您的情况下,您很可能会以不同的方式选择 select2。 希望有帮助。 对于 Ajax,请使用 $(".select2").val("").trigger("change")。这应该可以解决问题。 如果需要,此代码会删除显示新列表的所有结果: $('#select2Elem').data('select2').$results.children().remove() 例如省市列表中,当省份发生变化时,我们点击城市输入,旧城市列表仍然显示,直到新列表加载完毕。 用我写的代码,可以在调用ajax之前删除旧列表 因为它们都不适合我(select2 4.0.3),所以采用了标准选择方式。 for(var i = selectbox.options.length - 1 ; i >= 0 ; i--) selectbox.remove(i); 您可以使用此或进一步参考此https://select2.org/programmatic-control/add-select-clear-items $('#mySelect2').val(null).trigger('change'); 我就是这样做的: $('#my_input').select2('destroy').val('').select2(); 2024 年底,显然,唯一可以让我在不干扰其他事件的情况下以程序方式清除 Select2(版本 4.0.13)选项的解决方案是隐藏在 Select2 文档中用于清除选择选项的解决方案 我用过 $('#mySelect2').val(null).trigger('change');
使用 select2 javascript 作为选择框,它基本上隐藏了实际的真实选择框,并为您提供了一个包含 ul li 列表的范围。 然而,li选项并没有实际的实际价值......
我第一次在我的项目中使用select2,我认为我满足了我的许多项目要求。然而,有一件事不是在他们的搜索框中。 当我单击 select2 元素时,博士...
我使用 select2 加载远程数据我发送 ajax 请求并正确获取响应,但 processResult 不运行,并且不会显示任何内容 JavaScript代码: var 格式产品= 函数(
我想把这个输入组中这个select2的边框半径设置为0 我想把这个输入组中这个select2的边框半径设置为0 <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-user"></i> </span> <input type="hidden" id="default_customer_id" value="1"> <input type="hidden" id="default_customer_name" value="KHÁCH LẺ"> <input type="hidden" id="default_customer_balance" value="0.0000"> <input type="hidden" id="default_customer_address" value=""> <select class="form-control mousetrap select2-hidden-accessible" id="customer_id" required="" name="contact_id" tabindex="-1" aria-hidden="true" aria-required="true"> <option selected="selected" value="">Enter Customer name / phone</option> <option value="1">KHÁCH LẺ</option> </select> <span class="select2 select2-container select2-container--default select2-container--focus" dir="ltr" style="width: 281.578px;"> <span class="selection"> <span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-customer_id-container"> <span class="select2-selection__rendered" id="select2-customer_id-container" title="KHÁCH LẺ">KHÁCH LẺ</span> <span class="select2-selection__arrow" role="presentation"> <b role="presentation"></b> </span> </span> </span> <span class="dropdown-wrapper" aria-hidden="true"></span> </span> <span class="input-group-btn"> <button type="button" class="btn btn-default bg-white btn-flat add_new_customer" data-name=""> <i class="fa fa-plus-circle text-primary fa-lg"></i> </button> </span> </div> 我尝试了以下代码,但它不起作用: .input-group .select2-container>.select2-container--default .select2-selection--single:not(:first-child):not(:last-child){border-radius:0} 你们能帮我吗?谢谢! 您的 CSS select 语句有两个主要问题。 第一 .select2-container--default 是 .select2-container 的 sibling,但您将其作为目标,就像它是它的子级一样(即 .select2-container>.select2-container--default) 第二个 虽然只有一个具有 .select2-selection--single 类的元素,并且您使用 .select2-selection--single:not(:first-child):not(:last-child) 来定位它,但选择器将不会匹配该元素。这是因为单个 .select2-selection--single 元素同时是第一个和最后一个子元素。 换句话说, :not(:first-child) 伪类将排除它,因为它是第一个子级,而 :not(:last-child) 伪类将排除它,因为它也是最后一个子级。因此,该元素不满足该选择器的条件,因此不会被定位。 因此,select语句应该是: .input-group .select2-container .select2-selection--single { border-radius: 0; }
引导程序版本:5.1.3 选择2版本:4.1.0 复制链接:https://jsfiddle.net/L60xwgmt/1/ $('.select2').select2({ dropdownParent: $('#dataModal'), ...
我如何仅使用javascript而不使用jquery从select2获取值
我试图通过更改事件获取 select2 的值,但我只找到了使用 jquery 的方法,并且我只想使用 javascript。 selectProduct.addEventListener('更改', () => { 反对...
我正在处理一个要求,即通过ajax提交表单后必须清除select2下拉框。我搜索并尝试了一些解决方案,但没有成功。 我的 select2 代码是: $(