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.
Related
I am having a jQuery plugin called Paginationjs running. Underscore is also involved, but this is not what this post is about, actually.
I want to add a text filter, so the server can filter before sending the response. Here's the code:
$(function() {
$('#pagination-container').pagination({
dataSource: 'pagination/api',
locator: 'data',
totalNumberLocator: function(response) {
// you can return totalNumber by analyzing response content
return response.totalAmount;
},
alias: {
pageNumber: 'pageNum',
pageSize: 'limit'
},
pageSize: 5,
ajax: {
url : 'pagination/api',
data: {
filter : $('#filter').val()
}
},
callback: function(data, pagination) {
var template = _.template($('#template-demo').html());
var html = template({data: data});
$('#data-container').html(html);
}
});
});
Whenever I change the page, the ajax call is fired, with the parameters filter, pageNum and limit attached to the url.
The filter value in that url stays the same during page changes: Empty. Even when I type things in that textfield with the ID "filter", it is still staying empty.
This plugin demands the setting called dataSource set, so I am forced to use the url there and also inside the ajax-setting called url.
Fun fact: When I have something entered in that text field and press F5 on Firefox, the browser keeps that content in that field after the refresh, and the entered value is sent to the server. The value for the url parameter "filter" is set then. But still, when I change the value and change pages, it's still the same value since the refresh of the site.
Is there any workaround to achieve this?
PS: I couldn't use the tag paginationjs because my reputation is below 1500.
So, since Paginationjs was initialising all the urls in the background with no possibility to change it the way as seen in my code above, here's a solution.
I added a button to re-initialize Paginationjs once it's clicked. This way, I don't need to use any Keypress-Event to send countless ajax requests to the server. I also changed the ID of the text field.
By re-initializing it, the filter value is getting attached with its value to the dataSource parameter. Ajax settings are not needed any longer.
$(function() {
var paginationSettings = {
dataSource: 'pagination/api',
locator: 'data',
pageSize: 5,
totalNumberLocator: function(response) {
return response.totalAmount;
},
alias: {
pageNumber: 'pageNum',
pageSize: 'limit'
},
callback: function(data, pagination) {
var template = _.template($('#template-demo').html());
var html = template({data: data});
$('#data-container').html(html);
}
}
$('#pagination-container').pagination(paginationSettings);
$('#filter-button').click(function() {
paginationSettings.dataSource = 'pagination/api?filter=' + $('#filter-text').val();
$('#pagination-container').pagination(paginationSettings);
});
});
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!
I've had a look at some other threads but nothing quite as specific. It's not really something that I would assume is hard but I'm not sure how about to do it.
Currently I'm using Select2 for a tagging system and next to it I have suggested tags which users would be able to click on and it will add to the box.
Instead, each tag is replacing the content and adding itself.
I need the adding to be appended into the box without replacing what's already in there.
Here's my code:
$(document).on('click', ".tag1", function () {
var value = $(".tag1").html();
console.log(value);
$("#selectPretty").val([value]).trigger("change");
});
$(document).on('click', ".tag2", function () {
var value = $(".tag2").html();
console.log(value);
$("#selectPretty").val([value]).trigger("change");
});
The data is being pulled through via AJAX with a span around each suggested tag.
Hope I'm clear enough.
Summary: I want to be able to click on each 'tag' and for it to be added, instead it replaces what was already in the box.
Thanks
You should be able to do that with simple:
var test = $('#test');
$(test).select2({
data:[
{id:0,text:"enhancement"},
{id:1,text:"bug"},
{id:2,text:"duplicate"},
{id:3,text:"invalid"},
{id:4,text:"wontfix"}
],
multiple: true,
width: "300px"
});
var data = $(test).select2('data');
data.push({id:5,text:"fixed"});
$(test).select2("data", data, true); // true means that select2 should be refreshed
Working example: http://jsfiddle.net/z96Ca/
You are replacing the value with val(mystuff). You want to do the following:
Get the current data in the input with val()
var dataOld = $('#selectPretty').val();
Append the new data with something like*
var dataNew = dataOld.push(value);
Set the input data to new data:
$('#selectPretty').val(dataNew);
*This assumes that val() returns an array
Docs
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();
I'd like to use jQuery's auto complete in a Drupal project to automatically find nodes (pieces of content) with a given title. I can't quite find any examples of option usage that match what I am trying to do, which is the following:
URL needs to conform to the pattern: /api/node/title/{whatever the user typed}
When results are returned as JSON, the title needs to be used in the auto complete list
When a result is clicked, a styled paragraph containing the title will appear over the text box, but it will actually contain the node id (nid) of the node selected.
Here is what I have so far:
jQuery(this).autocomplete({
source: '/api/node/title/'+jQuery(this).val(),
minLength: 2
}).data( "autocomplete")._renderItem = function(ul, item) {
return jQuery('<li />')
.data("item.autocomplete", item)
.appendTo(ul);
};
I haven't even gotten to worrying about what to do once an element is selected - the URL is going out as /api/node/title?term={blank}, and even though I am getting JSON results back, nothing is appearing. Any suggestions, or examples of similar usage? The examples on the jQuery UI website for autocomplete weren't especially helpful.
EDIT: Here is an example of the expected response.
{
"nid":"2",
"vid":"2",
"type":"lorem",
"language":"und",
"title":"Grid Computing",
"uid":"0",
"status":"1",
"created":"1320092886",
"changed":"1320273538",
"comment":"1",
"promote":"1",
"sticky":"0",
"tnid":"0",
"translate":"0"
}
for 1), you can use a callback for the source
$('input').autocomplete({
source: autoDrupal,
minLength: 2});
function autoDrupal(requestObject, responseCallback) {
var url = '/api/node/title/' + requestObject.term;
$.get(url, function(data) {
// check my fiddle to transform drupal response in autocomplete result ;)
responseCallback(data);
});
};
for 2) I don't get what you mean by "title" but it can surely be handled in the response of $.get
for 3) a event handler can do the trick (once I understand your dreaded "title"). something like that:
$('ul.ui-autocomplete').delegate('li', 'click', function () {
$('#stuff').css('color', 'red');
})
check and play with this fiddle ;)