Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

javascript - How to set default value on an input box with select2 initialized on it?

How do I set default value on an input box with select2? Here is my HTML:

<input type="text" id="itemId0" value="Item no. 1">

and my javascript:

$("#itemId0").select2({
    placeholder: 'Select a product',
    formatResult: productFormatResult,
    formatSelection: productFormatSelection,
    dropdownClass: 'bigdrop',
    escapeMarkup: function(m) { return m; },
    minimumInputLength:1,
    ajax: {
        url: '/api/productSearch',
        dataType: 'json',
        data: function(term, page) {
            return {
                q: term
            };  
        },  
        results: function(data, page) {
            return {results:data};
        }   
    }   
});

function productFormatResult(product) {
   var html = "<table><tr>";
   html += "<td>";
   html += product.itemName ;
   html += "</td></tr></table>";
   return html;
}

function productFormatSelection(product) {
    var selected = "<input type='hidden' name='itemId' value='"+product.id+"'/>";
    return selected + product.itemName;
}

Here is the issue:

If I won't initialize my input box into a select2 box, I can display the default value of my input box which is "Item no. 1": 1st

but when I initialize it with select2 eg. $("#itemId0").select2({code here}); I can't then display the default value of my text box: 2

Anyone knows how can I display the default value please?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to utilize the initSelection method as described in Select2's documentation.

From the documentation:

Called when Select2 is created to allow the user to initialize the selection based on the value of the element select2 is attached to.

In your case, take a look at the Loading Remote Data example as it shows how to incorporate it along with AJAX requests.

I hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...