質問

I would like to populate a select, but do not have the associated description. Only have value.

I am using (select2):

$( '#element' ).attr( "data-init-text", "" ).val( value ).change();

but does not work because I have no description

I'm using a hidden input as an ajax call.

役に立ちましたか?

解決

You need to get the text (which you call the description) for the id (which you call the value). Since you are using ajax for the Select2 data, you could use an ajax call to get the text for an id.

You would supply an initSelection function that makes the ajax call. It might look something like this:

initSelection: function(element, callback) {
    var id= $(element).val();
    if (id) {
        $.ajax('/this/is/the/url/', {
            data: { id: id },
            dataType: 'json',
            success: function(data) { callback(data); } });
    }
}

In this case the ajax call passes the "id" parameter and is expected to return json that looks like this:

{ id: 'the_passed_in_id', text: 'the_text_for_the_id' }

Demo on JSFiddle

他のヒント

Just create your normal select:

<select id='myId'>

 <option value='val1'>Option 1<option>

 <option value='val2'>Option 2<option>

</select>

$('#myId').select2();

That how you create a select2.

If you want to select an option:

$('#myId').select2('val', 'val2');

In this case Option 2 is selected.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top