Question

Here I have included scripts:

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type='text/javascript' src='//netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js'></script>
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<link href="http://ivaynberg.github.com/select2/select2-3.3.2/select2.css" rel="stylesheet" type="text/css" />
<script src="http://ivaynberg.github.com/select2/select2-3.3.2/select2.js"></script>

HTML:

<input  type="hidden" id="parcele" />

and jquery code on the bottom of page:

<script>
function formatValues(data) {
    return data.ime_prezime;
}

$('#parcele').select2({
    ajax: {
        dataType: "json",
        url: "json.php",
        results: function (data) {
            return {results: data};
        }
    },
    width: "300px",
    formatResult: formatValues,
    formatSelection: formatValues,
    multiple: true
});
</script>

but I get error: Uncaught TypeError: Object [object Object] has no method 'select2'

What is wrong here? I dont get it...

Was it helpful?

Solution

You need to wait until jQuery and select2.js have loaded:

function formatValues(data) {
    return data.ime_prezime;
}

$(document).ready(function() { // add this
    $('#parcele').select2({
        ajax: {
            dataType: "json",
            url: "json.php",
            results: function (data) {
                return {results: data};
            }
        },
        width: "300px",
        formatResult: formatValues,
        formatSelection: formatValues,
        multiple: true
    });
}); // add this

EDIT: I found your problems:

  1. You don't have any elements with id "parcele" on your actual page at http://agroagro.com/template/tema/zadaci.html# - I think you are thinking of the elements with id "parcela" (notice the "a" instead of an "e").

  2. You actually have two elements with the id "parcela", but HTML ids have to be unique.

To fix this: Rename one of the elements with the id "parcela", then use one of them where you have "parcele" in your existing JavaScript.

Also, just to verify that everything works if you fix the naming problems, I created this jsFiddle, which works correctly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top