I have next select2:
siteSelector = $('#siteSelector').select2(
{
placeholder : "Select site ...",
ajax : {
type : 'GET',
dataType : 'json',
contentType : 'application/json',
url : {url_of_my_rest_service},
data : function(term, page) {
return {
startswith : term,
};
},
results : function(data, page) {
var items = data.content;
var res = {
results : []
}, i;
for (i = 0; i < items.length; i++) {
res.results.push({
id : items[i].id,
text : items[i].name
});
}
return res;
}
},
minimumInputLength : 3
});
How can I make that when I press a dropdown button some values will already be preloaded in there?
The best way to do it is to insert the data in the DOM before calling the ajax.
$(document).ready(function () {
//as many as you need, using loop or manually
$('#siteSelector').append("<option value='value1'>Value 1</option>")
//only then start select2 using the function you wrote
//siteSelector = $('#siteSelector').select2(......
})
As far as I know, the data attribute in select2 doesn't work well (or at all) with ajax calls. This method will work.
Related
I have a script that get's some data from the backend and populates the select2 dropdown. The problem is that the ajax call is called 2 times always and it should not be like this. I am not sure what I am doing wrong... any help would be apreciated.
this is my code:
var select2Element = $('select').select2({
theme: "classic",
escapeMarkup: function (markup) { return markup; },
});
select2Element.on('select2:opening', function(event) {
var clicked = $(this);
var route = "{{ path('get_attribute_list', {'articleId': 'ARTICLEID', 'attributeGroupId': 'ATTRIBUTEGROUPID'}) }}"
var url = route.replace("ARTICLEID", $(this).attr('data-articleId')).replace('ATTRIBUTEGROUPID', $(this).attr("data-attributeGroupId"));
$.ajax ({
url: url,
dataType: 'json',
async: false,
type: "GET",
}).then(function (data) {
//#TODO get out elements already inserted
for (var d = 0; d < data.length; d++)
{
var item = data[d];
// Create the DOM option that is pre-selected by default
var option = new Option(item.text, item.id, true, true);
// Append it to the select
clicked.append(option);
}
// Update the selected options that are displayed
clicked.trigger('change');
});
});
var inputResult = [];
select2Element.on('select2:select', function(e) {
var jsonValue = {
"articleId": $(this).attr("data-articleId"),
"attributeGroupId": $(this).attr("data-attributeGroupId"),
"attributeId": e.params.data.id
}
inputResult.push(jsonValue);
$('#addAttributes').val(JSON.stringify(inputResult));
});
select2Element.on('select2:close', function() {
$(this).html('');
});
Seems there is a bug in 'select2:open' and 'select2:opening'. There is a fix for this but not published.
Anyway who has this problem until it is fixed can see more details here:
https://github.com/select2/select2/issues/3503
and the fix for this here:
https://github.com/select2/select2/commit/c5a54ed70644598529a4071672cca4a22b148806
I'm attempting to first make an AJAX request from a social API and append the results with a button inside the div that will save the corresponding item in the array to my firebase database. For example,
I have my AJAX request - I cut out about 75% of the actual code that isn't needed for the question.
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data){
console.debug(data);
vids = data.response.items;
for(var i in vids) {
dataTitle = vids[i].title;
ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase()'>Save</button></div>";
$('#content').append( ncode )
And then I have my function that I want to save the 'title' of the object the button was appended with to the firebase database.
var dataTitle;
function saveToDatabase() {
ref.push({
title: dataTitle
});
}
The issue is that when the button is clicked it posts a random title from inside the array instead of the title of the item the button was appended with... How can I bind the buttons function to the correct dataTitle?
I'm not sure if that makes sense so please let me know if clarification is needed. Thanks in advance for any help you can provide!
This fails because you are iterating the entire list and assigning them to a global variable. The result is not random at all--it's the last item in the list, which was the last to be assigned to the globar variable.
Try using jQuery rather than writing your own DOM events, and utilize a closure to reference the video title.
function saveToDatabase(dataTitle) {
ref.push({
title: dataTitle
});
}
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data) {
console.debug(data); // console.debug not supported in all (any?) versions of IE
buildVideoList(data.response.items);
}
});
function buildVideoList(vids) {
$.each(vids, function(vid) {
var $img = $('<img></img>');
$img.attr('src', sanitize(vid.title));
var $button = $('<button class="btn">Save</button>');
$button.click(saveToDatabase.bind(null, vid.title));
$('<div class="tile"></div>')
.append($img)
.append($button)
.appendTo('#content');
});
}
// rudimentary and possibly ineffective, just here to
// point out that it is necessary
function sanitize(url) {
return url.replace(/[<>'"]/, '');
}
I actually just ended up passing the index to the function by creating a global array like so. It seems to be working fine... any reason I shouldn't do it this way?
var vids = []; //global
function foo() {
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data){
console.debug(data);
vids = data.response.items;
for(var i in vids) {
ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase('+i+')'>Save</button></div>";
$('#content').append( ncode )
} //end ajax function
function saveToDatabase(i) {
ref.push({
title: vids[i].title
});
}
I am new to jQuery.
I have to reload a div after sending some values to server using ajax.
My jQuery code is
selectionChanged: function () {
var $selectedRows = $('#PersonTableContainer').jtable('selectedRows');
$selectedRows.each(function () {
var record = $(this).data('record');
var columnname = record.columnname;
var datatype = record.datatype;
var columnlength = record.columnlength;
$.post('meta?action=dataload', {
columnname: columnname, datatype: datatype, columnlength: columnlength
});
});
after this code is executed I want to reload a div
<div id="loadedtablecontainer"></div>
this div will get the selected data of 1st jtable .. and display it in this jtable.
So by using this div id I have to call or reload this div soon after above jQuery function got executed
Something like
$.post('meta?action=dataload', {
columnname: columnname, datatype: datatype, columnlength: columnlength
});
$("#loadedtablecontainer");
So I am assuming the Ajax call returns the new content, so set the html() in the callback.
$.post('meta?action=dataload',
{
columnname : columnname,
datatype:datatype,
columnlength:columnlength
},
function (data) {
$( "#loadedtablecontainer" ).html(data);
}
);
You have a callback parameter which returns your result from post. Use that to manipulate the data and form the HTML. Then simply append it
$.post('meta?action=dataload', {
columnname : columnname, datatype:datatype,columnlength:columnlength
},
function (result) {
// make your manipulations here, (Ex: var manipulatedHTML )
$("#loadedtablecontainer" ).append(manipulatedHTML );
}
);
If its a json
function(result) {
//result is your json
var manipulatedHTML = '<div class="result">'+result.value"+'</div>';
}
$("#loadedtablecontainer" ).append(manipulatedHTML )
Use a for loop if its a json array
function loadCustomerCorpPopup(id) {
$("#eBody").mask("${loading}");
$.ajax({
url : '${url}/customer/ajax_customer_corporate_popup',
data : {
customerCorporateId : id,
},
dataType : 'text',
cache : false,
success : function(data) {
$('#popupId').html(data);
$('#popupId').modal('show');
$("#eBody").unmask("${loading}");
}
});
}
You can use this way $('#popupId').html(data);
data can a html code or url.
Here is what i am trying http://jsfiddle.net/wQysh/347/
JS :
$.fn.editable.defaults.mode = 'inline';
var count = 4, sources = [];
for(var i = 1; i <= count; i++){
sources.push({ id : i, text : 's-'+String(i) })
}
var getSource = function() {
//i want this function must be called whenever available options is rendred. to ensure NO references issues, i used JSON.parse
return JSON.parse(JSON.stringify(sources));
};
var getQuery = function(options){
options.callback({ results : getSource() });
};
var getInitSel = function(multiple) {
return function(el, cb){
var t, toSet = [], sc = getSource();
el[0].value.split(',').forEach(function(a){
t = _.findWhere(sc, { id : Number(a.trim()) });
if(t) toSet.push(t);
});
cb(multiple ? toSet : (toSet.length ? toSet[0] : null));
};
};
$('#controller').click(function(e){
count++;
sources.push( {id : count, text : 's-'+String(count) });
$('#username').editable('option', 'source', getSource()); // <---------------- THIS LINE HAS NO EFFECT SO PRODUCING UNDESIRED RESULT
//with above line, the source option should get updated and should be handing the new records to render. but nothing happens such.
$('#username').editable('setValue', [1, count]);
});
$('#username').editable({ //to keep track of selected values in multi select
type: 'select2',
url: '/post',
autotext : 'always',
source : getSource(),
value : [1,2],
emptytext: 'None',
select2: {
multiple : true,
initSelection : getInitSel(true),
query :getQuery
}
});
//ajax emulation. Type "err" to see error message
$.mockjax({
url: '/post',
responseTime: 400,
response: function(settings) {
if(settings.data.value == 'err') {
this.status = 500;
this.responseText = 'Validation error!';
} else {
this.responseText = '';
}
}
});
I am just trying to update the source option of editable element via a controller. But the view doesn't reflect the same.
Any solution??
just added display function with iDkey as 'id'
$('#username').editable({ //to keep track of selected values in multi select
type: 'select2',
url: '/post',
autotext : 'always',
source : getSource(),
value : [1,2],
emptytext: 'None',
display: function(value, sourceData) {
//display checklist as comma-separated values
var html = [],
checked = $.fn.editableutils.itemsByValue(value, getSource(), 'id'); // it was needed to send 'id' as idKey otherwise it was fetching with value
if(checked.length) {
$.each(checked, function(i, v) { html.push($.fn.editableutils.escape(v.text)); });
$(this).html(html.join(', '));
} else {
$(this).empty();
}
},
select2: {
multiple : true,
initSelection : getInitSel(true),
query :getQuery
}
});
here is working code http://jsfiddle.net/wQysh/351/
Every time we 'setValue' to editable or on close event editable's 'display' function is called.
in display function existing values is checked by this function
$.fn.editableutils.itemsByValue
where the third parameter accepts the idKey. If we do not provide third parameter while calling this function, it by default takes 'value' as idKey. and 'value' as idKey should not be used when we are using to load array data. ref : http://ivaynberg.github.io/select2/#data_array.
I need to get a selected item from drop menu,
I am using this script : LINK
This is my code I just need to get values in javascript:
function checkData() {
var pagesObj = document.getElementById("website2");
alert(pagesObj.options[pagesObj.selectedIndex].value);
}
$(document).ready(function() {
$.ajax({
url: "get_data.php",
cache: false,
dataType: 'json',
data: {},
success: function(data) {
for (var i = 0; i < data.results.length; i++) {
if(data.results[i].value != '0' ) {
oHandler = $("#websites2").msDropDown().data("dd");
oHandler.add({text:'', value:'', title:''});
oHandler.add({text:data.results[i].text,value:data.results[i].value,title:data.results[i].title});
}
}
}
});
});
This checkData() function is giving me error that option is not defined and it is null
EDIT:
Html:
<select name="websites2" id="websites2" onChange="checkData()" style="width:200px;"tabindex="1"></select>
I believe it is as simple as this (using jQuery):
var selectedIndex = $("#websites2").val();
Since you have jQuery
$('#websites2').val()
should do it, though I've found that a bit unreliable on Opera just recently. The following works reliably for me on all the browsers I've tested:
$('#websites2 option:selected').val()