Add item to input programmatically

daGrevis picture daGrevis · Dec 8, 2013 · Viewed 11.9k times · Source

Selectize.js allows to transform inputs into widgets with tagging, auto-complete etc.. I'm trying to add tag into input using code.

Here's what I have so far.

$(function() {
    $("#tags").selectize({
        create: true
    })

    var selectize_tags = $("#tags")[0].selectize
    selectize_tags.createItem("foo")
    selectize_tags.refreshItems()
})

http://jsfiddle.net/qDL37/

Unfortunately, “foobar“ isn't added to input box. As far as I know, it's the correct way to do it.

Could this be a bug in selectize.js? I tried to search through GitHub issues, but couldn't find anything like that.

Also I tried to read code of selectize.js, but no luck.

Answer

daGrevis picture daGrevis · Dec 8, 2013

Thanks to great people from #javascript @freenode, this is the correct way.

$(function() {
    $("#tags").selectize({
        create: true
    })

    var selectize_tags = $("#tags")[0].selectize
    selectize_tags.addOption({
        text:'Foo',
        value: 'foo'
    });
    selectize_tags.addItem('foo')
    // selectize_tags.refreshItems()
})

http://jsfiddle.net/qDL37/1/