简体   繁体   English

jQuery 选择自动格式化

[英]jQuery Chosen with Auto-Formatting

I have one multi-select input box that uses jQuery Chosen.我有一个使用 jQuery 选择的多选输入框。 It currently has the functionality to add custom values that aren't in the existing list.它目前具有添加不在现有列表中的自定义值的功能。 However, I'm having a hard time trying to add an additional feature that basically formats the numbers that users type in automatically.但是,我很难尝试添加一个附加功能,该功能基本上可以格式化用户自动输入的数字。

For example:例如:

User input: 12142113114444用户输入: 12142113114444

Expected output: 1-2-1421:1311 ZIO 4444预期输出: 1-2-1421:1311 ZIO 4444

I've already handled the logic of formatting numbers.我已经处理了格式化数字的逻辑。 My issue is trying to tie it together with my jQuery Chosen input box.我的问题是试图将它与我的 jQuery Chosen 输入框联系起来。

My current input box code can be found here: https://jsfiddle.net/b6xupfak/我当前的输入框代码可以在这里找到: https : //jsfiddle.net/b6xupfak/

HTML HTML

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css">
    
<div style="padding: 20px;">

  <label>Bootstrap + jQuery Chosen</label>
  <div>
    <select id="num" data-placeholder="Enter a Number" class="chosen-select" style="width:350px;" tabindex="4" multiple>
            <option value="1-2-1421:1311 ZIO 4444">1-2-1421:1311 ZIO 4444</option>
            <option value="2-6-2862:2342 ZIO 0001">2-6-2862:2342 ZIO 0001</option>
            <option value="9-4-0082:3922 ZIO 7352">9-4-0082:3922 ZIO 7352</option>
    </select>   
  </div>

  <label>Bootstrap</label>
  <div>
    <input id="num_no_jqc" class="form-control" maxlength="21">
  </div>
  
</div>

I have a JavaScript function that implements the formatting for the second input box and it works as intended.我有一个 JavaScript 函数,它实现了第二个输入框的格式,它按预期工作。 However, when I try to apply it to the input box that has jQuery Chosen, it doesn't work.但是,当我尝试将其应用于具有 jQuery 选择的输入框时,它不起作用。

$('.chosen-select').chosen({}).change( function(obj, result) {
    console.debug("changed: %o", arguments);
    console.log("selected: " + result.selected);
});

$(function (){

                                $("#num").on("chosen:no_results", function (evt, params) {
                    let elem = $("#num").siblings(".chosen-container").find(".chosen-choices .search-field:last input");
                    let text = elem.val().replace(/'/g, "");
                    text = `<button class="btn btn-success" onClick="addCustomNum('${text}')" style="height: 30px; font-size: 15px;">Add NEW TMK: '${text}'</button>`;
                    $("#num").siblings(".chosen-container").find(".no-results").html(text);
                    });
});

                                function addCustomNum(searchStr) {
                        let arr = $("#num").val();
                        $("#num").html($("#num").html() + "<option value='" + searchStr + "'>" + searchStr + "</option>");
                        $("#num").val(arr.concat([searchStr]));
                        $("#num").trigger("chosen:updated");
                                }


$(function () {

            $('#num').keydown(function (e) {
                var key = e.charCode || e.keyCode || 0;
                $text = $(this);
                if (key !== 8 && key !== 9) {
                    if ($text.val().length === 1) {
                        $text.val($text.val() + '-');
                    }
                    if ($text.val().length === 3) {
                        $text.val($text.val() + '-');
                    }
                    if ($text.val().length === 7) {
                        $text.val($text.val() + ':');
                    }
                    if ($text.val().length === 12) {
                        $text.val($text.val() + ' ZIO ');
                    }
                }
                return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
            })
            
            
            $('#num_no_jqc').keydown(function (e) {
                var key = e.charCode || e.keyCode || 0;
                $text = $(this);
                if (key !== 8 && key !== 9) {
                    if ($text.val().length === 1) {
                        $text.val($text.val() + '-');
                    }
                    if ($text.val().length === 3) {
                        $text.val($text.val() + '-');
                    }
                    if ($text.val().length === 7) {
                        $text.val($text.val() + ':');
                    }
                    if ($text.val().length === 12) {
                        $text.val($text.val() + ' ZIO ');
                    }
                }
                return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
            })        
});

It seems that jQuery Chosen has a specific element that might be responsible for handling user input, but I can't quite figure out what it is.似乎 jQuery Chosen 有一个可能负责处理用户输入的特定元素,但我不太清楚它是什么。

When you are using multiple in a select element, it basically creates a new element with the existing one in the DOM.当您在 select 元素中使用multiple时,它基本上会使用 DOM 中的现有元素创建一个新元素。 If you check through the dev tool, you will find it.如果你通过开发工具检查,你会找到它。 So when you were actually trying to get the input value using the Id -> num , it actually made a different Id and input field in the DOM.因此,当您实际尝试使用Id -> num获取输入值时,它实际上在 DOM 中创建了不同的 Id 和输入字段。

instead of trying this:而不是尝试这个:

$('#num').keydown(function (e) {}

try to use this:尝试使用这个:

$("#num_chosen").find("input").keydown( function (e) {}

If you open the dev tool, you will see it made a new div with id -> num_chosen and with an input element, all I did is try to find that element and it worked fine.如果你打开开发工具,你会看到它用id -> num_chosen和一个输入元素id -> num_chosen了一个新的 div,我所做的就是尝试找到该元素并且它工作正常。

Workable Fiddle可行的小提琴

You might want to provide further logic according to your needs.您可能希望根据需要提供进一步的逻辑。

Note: I am not an expert in DOM manipulation so my explanation won't be that good as pros give.注意:我不是 DOM 操作方面的专家,所以我的解释不会像专业人士给出的那么好。

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

相关问题 将输入字段自动格式化为用户类型 - Auto-formatting input fields as user types 在Eclipse中自动格式化JavaScript代码 - Auto-formatting of JavaScript code in Eclipse 禁用 TinyMCE 自动格式化内容行为 - disabling TinyMCE auto-formatting content behavior VSCode 将多行代码自动格式化为一行代码 - VSCode is auto-formatting multiline to one line code 在Aptana Studio 3中将Java数组自动格式化为新行 - Auto-formatting Javascript arrays into new lines in Aptana Studio 3 WebStorm自动格式化为SQL模板文字添加了领先的空格 - WebStorm auto-formatting adds leading whitespace to SQL template literals 在RTF编辑器中覆盖IE电子邮件自动格式化 - Override IE email auto-formatting in rich-text editor 有没有办法防止VSCode自动格式化在问号和单词之间添加空格 - Is there a way to prevent VSCode auto-formatting from adding a space between question marks and words 防止Atom Beautify自动格式化es6导入/对象解构(反应) - Prevent Atom Beautify from auto-formatting es6 import/object de-structuring (React) 通过将HTML放入“标签”响应中,jQuery自动完成格式化 - JQuery auto-complete formatting by putting HTML in “label” response
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM