I'm trying to programmatically clear a drop down using the fantastic Select2 library. The drop down is dynamically filled with a remote ajax call using the Select2 query option.
HTML:
<input id="remote" type="hidden" data-placeholder="Choose Something" />
Javascript:
var $remote = $('#remote');
$remote.select2({
allowClear: true,
minimumInputLength: 2,
query: function(options){
$.ajax({
dataType: 'json',
url: myURL + options.term,
error: function(jqXHR, textStatus, errorThrown){
smoke.alert(textStatus + ": server returned error on parsing arguments starting with " + options.term);
},
success: function(data, textStatus, jqXHR){
var results = [];
for(var i = 0; i < data.length; ++i){
results.push({id: data[i].id, text: data[i].name});
}
options.callback({results: results, more: false});
}
});
}
});
Unfortunately, the call to $remove.select2('val', '') throws the following exception:
Uncaught Error: cannot call val() if initSelection() is not defined
I've tried setting the attr, setting the val, text and the Select2 specific data function. Can't seem to make the guy clear and work in a radio button like manner. Anyone got suggestions?
This works for me:
$remote.select2('data', {id: null, text: null})
It also works with jQuery validate when you clear it that way.
--
edit 2013-04-09
At the time of writing this response, it was the only way. With recent patches, a proper and better way is now available.
$remote.select2('data', null)
In case of Select2 Version 4+
it has changed syntax and you need to write like this:
// clear all option
$('#select_with_blank_data').html('').select2({data: [{id: '', text: ''}]});
// clear and add new option
$("#select_with_data").html('').select2({data: [
{id: '', text: ''},
{id: '1', text: 'Facebook'},
{id: '2', text: 'Youtube'},
{id: '3', text: 'Instagram'},
{id: '4', text: 'Pinterest'}]});
This is the proper one, select2 will clear the selected value and show the placeholder back .
$remote.select2('data', null)
For select2 version 4 easily use this:
$('#remote').empty();
After populating select element with ajax call, you may need this line of code in the success section to update the content:
success: function(data, textStatus, jqXHR){
$('#remote').change();
}
Using select2 version 4 you can use this short notation:
$('#remote').html('').select2({data: {id:null, text: null}});
This passes a json array with null id and text to the select2 on creation but first, with .html('') empties the previously stored results.
You should use this one :
$('#remote').val(null).trigger("change");
Method proposed #Lelio Faieta is working for me, but because i use bootstrap theme, it remove all bootstrap settings for select2. So I used following code:
$("#remote option").remove();
I'm a little late, but this is what's working in the last version (4.0.3):
$('#select_id').val('').trigger('change');
This solved my problem in version 3.5.2.
$remote.empty().append(new Option()).trigger('change');
According to this issue you need an empty option inside select tag for the placeholder to show up.
These both work for me to clear the dropdown:
.select2('data', null)
.select2('val', null)
But important note: value doesn't get reset, .val() will return the first option even if it's not selected. I'm using Select2 3.5.3
I found the answer (compliments to user780178) I was looking for in this other question:
Reset select2 value and show placeholdler
$("#customers_select").select2("val", "");
From >4.0 in order to really clean the select2 you need to do the following:
$remote.select2.val('');
$remote.select2.html('');
selectedValues = []; // if you have some variable where you store the values
$remote.select2.trigger("change");
Please note that we select the select2 based on the initial question. In your case most probably you will select the select2 in a different way.
Hope it helps.
For Ajax, use $(".select2").val("").trigger("change"). That should solve the issue.
this code remove all results for showing new list if you need:
$('#select2Elem').data('select2').$results.children().remove()
For example, in the list of provinces and cities, when the province changes and we click on the city input, the list of old cities is still displayed until the new list is loaded.
With the code I wrote, you can delete the old list before calling ajax
Since none of them all worked for me (select2 4.0.3) is went the std select way.
for(var i = selectbox.options.length - 1 ; i >= 0 ; i--)
selectbox.remove(i);
You can use this or refer further this https://select2.org/programmatic-control/add-select-clear-items
$('#mySelect2').val(null).trigger('change');
This is how I do:
$('#my_input').select2('destroy').val('').select2();
Related
I am using jquery-ui autocomplete plugin.
Here is how I've instantiated the autocomplete plugin.
//autofill
$( "#TextArea" ).autocomplete({
source: "search.php?option="+ option.toLowerCase(),
minLength: 3
});
On dropdown change, i am trying to change the option :
$('#Options').on('change', function() {
option = this.value.toLowerCase();
var teaxtarea = $('#TextArea');
//this is supposed to change the source string when the option value changes.
teaxtarea.autocomplete( "option", "source", "search.php?option="+ option);
}
});
I got the code to update the source string from the question below.
Jquery: Possible to dynamically change source of Autocomplete widget?
However, this solution doesn't seem to work for me.
I still get the first selected option even if i change the option in the dropdown.
Any help is greatly appreciated.
Suggest the following:
$("#TextArea").autocomplete({
source: function(req, resp){
var option = $('#Options option:selected').val().toLowerCase();
$.ajax({
cache: false,
url: "search.php",
data: {
option: option,
term: req.term
},
dataType: "json",
success: function(data){
resp(data);
}
});
},
minLength: 3
});
I think one issue is that if #Options is a <select> element, you need to find the selected child element:
$("#Options option:selected")
This ensures that you have the proper object and then you can call .val() upon it. If you need more help here, please update your post with an MCVE: https://stackoverflow.com/help/mcve
That may resolve the issue for you. If not, continue on.
Second, to ensure you are not caching, we can perform a more manual source capture.
When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must support CORS). The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results.
So we replicate the same functionality with some added settings. So each time source is checked, the options will be checked and the term will be sent. We'll get the data back in JSON and send back to Autocomplete to be displayed.
Hope that helps.
I'm using with satisfaction the library jAlert v4 available here
But I noticed that is not possible to use this library such as a simple "prompt" (that is a simple alert with a textbox) as shown in the following code:
var qnt = prompt("Insert")
Also this library is excellent because it automatically recognize all "alert()" functions in my code and applies his styles without any further implementation (it needs only to add its libraries inside <head> tag).
I discovered that there is also the "jQuery Alert Dialogs" library for my purpose, but it isn't customizable as jAlert v4.
So I would like to know if is possible to use the same library (jAlert v4) for my purpose, because I like the jalert customization (for ex. themes and animations) and it is very easy to use.
And I want to keep the same style like my jAlert as picture below: jAlert example but with a input TextBox.
That library is overriding the browser's built-in alert() function. You can do the same with prompt(), and have it open a jAlert with a text box on it.
window.prompt = function(title, value){
$.jAlert({
# Add an input field
'content': '<form><label>'+title+'</label><input value="'+(value||'')+'"></form>'
# Add the buttons or whatever else you need to the jAlert
});
};
The browser dialog stuff, such as alert, confirm and prompt are all blocking. JavaScript execute stops as those run.
There is simply no way to reproduce that behavior in external code, which means that one has to resort to using callbacks.
For some things, such as alert it may not be an issue .. if the code continues while the alert is still displayed, but it will fall apart if you try to show several alerts in a row.
For prompt and confirm, however, you will have to restructure your code.
I did a quick read of the jAlert docs and I saw both alert and confirm -- they didn't seem to have a prompt replacement, so I couldn't show their demo code
It might be worth checking out this library instead:
http://alertifyjs.com/
Yes, you can. If you just put the input box into the content, that will not appears, it's true. This is why you have the onOpen callback:
$.alertOnClick('.getTopClose', {
'title':'Textbox example',
'content':'', //Add nothing to the content
'onOpen': function(alert){
//This is the important part!
//Append a text input to the class .ja_body
$('.ja_body').append('<input type="text" name="something" value="" />');
}
});
I find a solution for my issue. And It's simply because always using the same jalert library. In my cause I use the returned value of my alert to perform an UPDATE via ajax. This is my code:
$.jAlert({
'title': 'Inserimento numero colli',
'content': '<form style="text-align:center;"><label>Quantita</label><br><input id="id_qnt" type="text" style="text-align:center"></form>',
'btns': [
{
'text': 'Save',
'closeAlert': 'false',
'onClick': function (e, btn) {
var item = btn.parents('.jAlert'),
form = item.find('form'),
error = false;
var field = form.find('input:text').val();
if (field == 'undefined' || field == '') {
error = "Empty quantity!";
}
if (!($.isNumeric(field))) {
error = "IsNan!"
}
if (field < 0) {
error = "IT'S < 0"
}
if (error) {
errorAlert(error);
return false;
}
// 'field' is the returned value... such as when using 'prompt'
// In my case I use it for AJAX
var obj = {};
obj.value = field;
$.ajax({
type: "POST",
url: "Master.aspx/UpdateItem",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
successAlert('SUCCESSFULLY SENT!', r.d);
}
});
// DYNAMICALLY CHANGE VALUE INSIDE PAGE change clicked_id by passing your id
document.getElementById(clicked_id).textContent = obj.value;
}
},
{
'text': 'Cancel'
}
]
});
It looks like this screenshot
I hope will be helpful to everyone!
In a nutshell, I'm trying to have an input generated, with a label created after the fact. However, instead of the expected label html being created, no label is shown, no errors show up in jsfiddle (although it doesn't work there either), and no error is presented when executing the code. Not even anything in the developer console in chrome. Here's the code snippet that I'm using to attempt this.
fieldset.append($('<input/>').attr({ type: 'radio', name: 'category', value: key, id: key}).click( function() { highLightButton("selected", key); hideShowText("show"); }).after("<label for='" + key + "'>AAA</label>"));
Am I binding it incorrectly? Perhaps a separate append call needs to be made? From what examples I've seen it should work, and yet it seems to just ignore the code.
jsFiddle URL as requested
http://jsfiddle.net/bL7heuoc/
Try this:
var $input = $('<input/>');
$input.attr({
type: 'radio',
name: 'category',
value: 'abc',
id: '123'
}).click(function (e) {
console.log('click');
});
$('body').append($input);
$input.after("<label for='123'>AAA</label>");
JSFiddle Demo: http://jsfiddle.net/sz29u00s/
#Jim is right, basically for "after" to work you need that the element has a parent (that at the end is where the new element will be added). that is why it works when you first append to the DOM and then call the after method.
I've been working with PHP for a while. I just started learning how to work with JSON.
I was able to create a PHP file that returns JSON. In my main file, I reference the PHP file and get the JSON objects.
I can display the objects in a dropdown select menu like this:
$.getJSON( "folder/services.php", function( data )
{
$.each(data, function(index, item)
{
$('#service').append($("<option>" + item.SERVICE + "</option>"));
});
});
The above code works fine. I can display the SERVICE values in the dropdown SELECT options.
What I am trying to figure out is how to get the SERVICE into the VALUE of the OPTION. I hope I am saying that correctly.
Typically, the OPTION tag would look like this:
<option value="SERVICE_A">Service A</option>
<option value="SERVICE_B">Service B</option>
...
But since I'm using JSON, I am not sure how to get the value into the OPTION.
I attempted to use PHP inside of the JQuery, but was unsuccessful. I'll show you what I attempted:
$('#service').append($("<option value='".+ item.SERVICE +."'>" + item.SERVICE + "</option>"));
****** EDIT ******
I attempted this piece of code submitted by LShetty below:
$.getJSON( "folder/services.php", function( data )
{
var strToAppend = "";
$.each(data, function(index, item)
{
strToAppend += $("<option/>",
{
'value': item.SERVICE,
'text': item.SERVICE
});
});
$('#service').append(strToAppend);
});
I only came up blank with this code. Does anyone see what I did wrong?
You're on the right track. Don't try to use . for concatentation in JS, though; it's a PHP thing. And .+ doesn't work in either language.
A safer, more jQuery-ish way to do this (it will work when ", ', <, etc. are present in the SERVICE value):
$('<option>').
attr('value', item.SERVICE).
text(item.SERVICE).
appendTo($('#service'));
Paul has the answer above. This is more of an optimization take. Modifying DOM in a loop is costly! it may be okay in this specific question as I only see 2 items. Hence, always construct your string outside of the loop and append all at once when you are ready.
var strToAppend = "";
$.each(data, function(index, item) {
strToAppend += $("<option/>", {
'value': item.SERVICE,
'text': item.SERVICE
});
});
$('#service').append(strToAppend);
Hope that helps :)
I finally managed to retrieve a list from the available options related to the name searched from a field. Now, my goal is to retrieve some extra info when the user selects a specific option from the list. The JSON returns only the last name of the person and the user id which is an auto-increment field in the database. So I thought that I could send another JSON request to the server to actually return all the information available from the person specified from the user id. Is this considered bad practice ? Is there something alternative I am maybe missing ?
All in all, my code is here:
<script>
$(function() {
$( "#search" ).autocomplete({
delay: 0,
minLength: 2,
source: function(request, response) {
$.ajax({
url: 'search.php',
data: { term: request.term },
success: function(data) {
data = JSON.parse(data);
response($.map(data, function(item) {
return {
label: item.firstName,
value: item.firstName};
}));
}
});
}
})
});
</script>
So, how am I supposed to achieve this ?
I searched similar threads and read the doc in the official site but couldn't find a way to start. I think that somehow the results returned from the first call should be appended to DOM with anchor links, this code should be placed to the select property if I am not mistaken. But, I am very new to jquery and these web stuff and can't figure out the way.
Any help will be much appreciated. Thank you in advance.
It all depends on how much extra data you need returned.
If it's not much, then it makes sense to return the data as extra properties in a list of objects you are returning for the autocomplete results.
If you think you need too much extra data to make that viable, then in the autocomplete's select callback, you can just use the ID value to fetch all the additional info in an additional AJAX call to a second web service that returns the persons details for the passed in ID value.