Home > Net >  jQuery Chosen with Auto-Formatting
jQuery Chosen with Auto-Formatting

Time:11-11

I have one multi-select input box that uses jQuery Chosen. 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

Expected output: 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.

My current input box code can be found here: https://jsfiddle.net/b6xupfak/

HTML

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/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/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU 6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/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. However, when I try to apply it to the input box that has jQuery Chosen, it doesn't work.

$('.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  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.

CodePudding user response:

When you are using multiple in a select element, it basically creates a new element with the existing one in the 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.

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.

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.

  • Related