developer tip

selectize.js 입력 값을 설정하는 방법은 무엇입니까?

copycodes 2021. 1. 10. 17:27
반응형

selectize.js 입력 값을 설정하는 방법은 무엇입니까?


입력에 일부 기본값을 복사하려는 양식이 있습니다. 양식 입력은 selectize.js 플러그인을 사용하고 있습니다. 프로그래밍 방식으로 일부 양식 값을 설정하고 싶습니다. 이를 수행하는 표준 방법 :

$("#my_input").val("My Default Value");

작동하지 않습니다.

나는 이와 같은 것을 시도했지만 작동하지 않습니다.

var $select = $("#my_input").selectize();
var selectize = $select[0].selectize;
selectize.setValue("My Default Value"); 

어떤 아이디어? 그것은 쉬울 것입니다 :) 나는 그것을 놓치고 있습니다.


API 문서 확인

방법 addOption(data)setValue(value)당신이 찾고있는 것일 수 있습니다.


업데이트 :이 답변의 인기를 보아 댓글 / 요청에 따른 추가 정보가 있습니다 ...

setValue(value, silent)
  선택한 항목을 주어진 값으로 재설정합니다.
  " silent "가 사실이면 (예 : true, 1) 원래 입력에서 변경 이벤트가 발생하지 않습니다.

addOption(data)
  사용 가능한 옵션 또는 옵션 배열을 추가합니다. 이미 존재하면 아무 일도 일어나지 않습니다.
  참고 : 이것은 옵션 목록 드롭 다운을 새로 고치지 않습니다 (사용 refreshOptions()).


덮어 쓰기 된 옵션에 대한 응답 :
이것은 처음에 제공 한 옵션을 사용하지 않고 선택을 다시 초기화하면 발생할 수 있습니다. 요소를 다시 만들지 않으려면 selectize 개체를 변수에 저장하면됩니다.

// 1. Only set the below variables once (ideally)
var $select = $('select').selectize(options);  // This initializes the selectize control
var selectize = $select[0].selectize; // This stores the selectize object to a variable (with name 'selectize')

// 2. Access the selectize object with methods later, for ex:
selectize.addOption(data);
selectize.setValue('something', false);


// Side note:
// You can set a variable to the previous options with
var old_options = selectize.settings;
// If you intend on calling $('select').selectize(old_options) or something

이것은 나를 위해 작동합니다.

var $select = $("#my_input").selectize();
var selectize = $select[0].selectize;
selectize.setValue(selectize.search("My Default Value").items[0].id);

그러나 당신은 정말로 당신이 하나의 일치 만 가지고 있다는 것을 정말로 확신해야합니다.

업데이트 :이 솔루션은 완벽하게 작동하므로 페이지에 여러 선택 요소가 있어도 작동하도록 순서대로 답변을 업데이트했습니다.

다음과 같이 초기화 할 수 있습니다.

$('select').each(function (idx) {
    var selectizeInput = $(this).selectize(options);
    $(this).data('selectize', selectizeInput[0].selectize);
});

초기화 후 실용적으로 값 설정 :

var selectElement = $('#unique_selector').eq(0);
var selectize = selectElement.data('selectize');
if (!!selectize) selectize.setValue("My Default Value");

사용자 'onlyblank'의 답변이 맞습니다. 그에 대한 작은 추가-원하는 경우 둘 이상의 기본값을 설정할 수 있습니다.

id를 setValue ()에 전달하는 대신 배열을 전달하십시오. 예:

var $select = $("#my_input").selectize();
var selectize = $select[0].selectize;
var yourDefaultIds = [1,2]; # find the ids using search as shown by the user onlyblank
selectize.setValue(defaultValueIds);

다음은 원격 검색에서 태그를 사용하는 전체 코드입니다. 이것이 도움이되기를 바랍니다.

$('#myInput').selectize({
valueField: 'id',
labelField: 'name',
searchField: 'name',
options: [],
delimiter: ',',
persist: false,
create: false,
load: function(query, callback) {
    if (!query.length) return callback();
    $.ajax({
        url: '/api/all_cities.php',
        type: 'GET',
        dataType: 'json',
        data: {
            name: query,
        },
        error: function() {
            callback();
        },
        success: function(res) {
            callback(res);
        }
    });
},
onInitialize: function(){
    var selectize = this;
    $.get("/api/selected_cities.php", function( data ) {
        selectize.addOption(data); // This is will add to option
        var selected_items = [];
        $.each(data, function( i, obj) {
            selected_items.push(obj.id);
        });
        selectize.setValue(selected_items); //this will set option values as default
    });
}
});

참고 setValue 는 값이 동적 일 수있는 컨트롤 (예 : 사용자가 즉석에서 값을 추가 할 수 있음, 텍스트 상자 필드)에 대해 selectize 컨트롤 (예 : select field)에 대해 미리 정의 된 값 집합이 이미있는 경우에만 작동합니다. setValue ai n't gonna 작업.

selectize 필드의 현재 값을 추가하고 설정하는 대신 createItem 기능을 사용하십시오.

전의.

$selectize[ 0 ].selectize.clear(); // Clear existing entries
for ( var i = 0 ; i < data_source.length ; i++ ) // data_source is a dynamic source of data
    $selectize[ 0 ].selectize.createItem( data_source[ i ] , false ); // false means don't trigger dropdown

방금 같은 문제가 발생하여 다음 코드 줄로 해결했습니다.

selectize.addOption({text: "My Default Value", value: "My Default Value"});
selectize.setValue("My Default Value"); 

I was having this same issue - I am using Selectize with Rails and wanted to Selectize an association field - I wanted the name of the associated record to show up in the dropdown, but I needed the value of each option to be the id of the record, since Rails uses the value to set associations.

I solved this by setting a coffeescript var of @valueAttr to the id of each object and a var of @dataAttr to the name of the record. Then I went through each option and set:

 opts.labelField = @dataAttr
 opts.valueField = @valueAttr

It helps to see the full diff: https://github.com/18F/C2/pull/912/files


A simplified answer:

$('#my_input').data('selectize').setValue("Option Value Here");

I had a similar problem. My data is provided by a remote server. I want some value to be entered in the selectize box, but it is not sure in advance whether this value is a valid one on the server.

So I want the value to be entered in the box, and I want selectize to show the possible options just if like the user had entered the value.

I ended up using this hack (which it is probably unsupported):

var $selectize = $("#my_input").selectize(/* settings with load*/);
var selectize = $select[0].selectize;
// get the search from the remote server
selectize.onSearchChange('my value');
// enter the input in the input field
$selectize.parent().find('input').val('my value');
// focus on the input field, to make the options visible
$selectize.parent().find('input').focus();

First load select dropdown and then selectize it. It will work with normal $(select).val().

ReferenceURL : https://stackoverflow.com/questions/21962124/how-to-set-a-value-for-a-selectize-js-input

반응형