Javascript Make Select 2 Use Url Set By Outside Source
I'm using select2 to pick out games from a database, however, the file I wish it to search from will change depending on what's selected from a dropdown. How do I get it so select2
Solution 1:
Found the answer here: https://github.com/select2/select2/issues/1679#issuecomment-280080742
var someCondition
ajax: {
url: function() {
if (someCondition) {
return '/api/1/someFile.json'
} else {
return '/api/1/someOtherFile.json'
}
}
}
Solution 2:
I suggest to use dynamic-urls, like the code below:
$('#mySelect2').select2({
ajax: {
url: function (params) {
return '/some/url/' + params.term;
}
}
});
Inside url function you can test other variables than params, like in the following snippet:
$('#category').select2({
placeholder: "Select category...",
width: '100%',
});
$('#category').on('select2:select', function(e) {
var data = e.params.data;
console.log("category", data);
categ = e.params.data.id;
});
var categ = "1";
$('#project').select2({
placeholder: "Select item...",
width: '100%',
ajax: {
type: "GET",
url: function(params) {
console.log("ajax func", params, categ);
var url = 'https://jsonplaceholder.typicode.com/comments?postId=' + categ
return url;
},
cache: true,
processResults: function(data) {
return {
results: $.map(data, function(obj) {
return {
id: obj.id,
text: obj.name
};
})
};
},
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" />
<div class="group">
<select id="category">
<option value="1">cat 1</option>
<option value="2">cat 2</option>
</select>
</div>
<br>
<div class="group">
<select id="project">
<option value=""></option>
</select>
</div>
Solution 3:
I would save off your default options and then recreate the select2 whenever you need to by extending your new URL into the default options:
var defaultOptions = {
selectOnClose: true,
width: '100%',
ajax: {
url: "test1.php",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: $.map(data, function(obj) {
return { id: obj.id, text: obj.text };
})
};
},
cache: true,
minimumInputLength: 2
};
//Use default to create first time
$(".game_picker").select2(defaultOptions);
//On change, recreate
$(document).on('change', ".category_select", function(e)
{
var options = defaultOptions;
if ($(this).val() == 16)
{
//Create a new options object with the url updated
options = $.extend({}, defaultOptions, { url: 'test2.php' });
}
//Create a select2 with the desired options
$(".game_picker").select2(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Post a Comment for "Javascript Make Select 2 Use Url Set By Outside Source"