Im knocking my head to this scripts and I cant get my function to be displayed inside the Aletify.js alerts.
Some help will be incredibly helpful ;-)
The Function:
Oshoplang = {
// System Message Text
RemoveError: '<p>This item has now been removed from your cart.\n\nThank you.',
Added: 'Has now been added to your cart',
OutOfStock: '<p>This item is not currently available or is out of stock.</p>',
PreOrder: '<p>Your pre-order has been made successfully.\n\nThank you.</p>',
InvalidQuantity: '<p>It looks like you entered an invalid quantity.\n\nPlease try again.</p>',
}
window.alert = function() {};
$("#confirm-else").on('click', function() {
reset();
$('#e-content').addClass('blur');
alertify.alert(Oshoplang, function(e) {
if (e) {
alertify.success("OK");
$('#e-content').removeClass('blur');
location.reload();
} else {
alertify.error("You've clicked Cancel");
}
});
return false;
});
I normally don't get a message on the run, but this way but i believe i'm close somewhere :-)
Not sure if you're still having this issue, but I believe that the alertify.alert function doesn't have any callbacks, as it's just a way to show a message. You're probably looking for the alertify.confirm instead.
The message is also not showing up because the first argument to alertify.alert or alertify.confirm needs to be a string. In your example, you're passing an object.
I've set up a demo of your code which has been adjusted to work on here on JSFiddle.
For what it's worth, the code sample is using an older version of alertify (0.3) and it has been updated, so that version 1 which is now out would have a somewhat adjusted syntax.
I have a Select2 auto-complete input (built via SonataAdmin), but cannot for the life of me figure out how to programmatically set it to a known key/value pair.
There's a JS Fiddle here that shows roughly what I have. What I want to know is what function I can attach to the button so that
the Select2 field shows the text "NEW VALUE" to the user, and
the Select2 field will submit a value of "1" when the form is sent to the server
I have tried all sorts of combinations of jQuery and Select2 data and val methods, called against various inputs on the page, but nothing seems to work... surely there's some way to do this?
-- Edit --
The accepted answer below is very useful, helps shed some light on the right way to initialise the selection and explains what initSelection is for.
Having said that, it seems that my biggest mistake here was the way I was trying to trigger the change.
I was using:
$(element).select2('data', newObject).trigger('change');
But this results in an empty add object inside select2's change event.
If, instead, you use:
$(element).select2('data', newObject, true);
then the code works as it should, with the newObject available in select2's change event and the values being set correctly.
I hope this extra information helps somebody else!
Note this was tested with version 4+
I was finally able to make progress after finding this discussion: https://groups.google.com/forum/#!topic/select2/TOh3T0yqYr4
The last comment notes a method that I was able to use successfully.
Example:
$("#selectelement").select2("trigger", "select", {
data: { id: "5" }
});
This seems to be enough information for it to match the ajax data, and set the value correctly. This helped immensely with Custom Data Adapters.
Note: For multi select, execute the above code for each item, like this :
// for each initially selected ids, execute the above code to add the id to the selection.
[{id: 5, text: 'op5'}, {id: 10, text: 'op10'}].forEach(option => {
$("#selectelement").select2("trigger", "select", {data: { id: option.id, text: option.text }});
})
Note: The Question and this Answer are for Select2 v3. Select2 v4 has a very different API than v3.
I think the problem is the initSelection function. Are you using that function to set the initial value? I know the Select2 documentation makes it sound like that is it's purpose, but it also says "Essentially this is an id->object mapping function," and that is not how you have implemented it.
For some reason the call to .trigger('change') causes the initSelection function to get called, which changes the selected value back to "ENABLED_FROM_JS".
Try getting rid of the initSelection function and instead set the initial value using:
autocompleteInput.select2('data', {id:103, label:'ENABLED_FROM_JS'});
jsfiddle
Note: The OP has supplied the formatResult and formatSelection options. As supplied, those callback functions expect the items to have a "label" property, rather than a "text" property. For most users, it should be:
autocompleteInput.select2('data', {id:103, text:'ENABLED_FROM_JS'});
More info on the initSelection function:
If you search through the Select2 documentation for "initSelection", you will see that it is used when the element has an initial value and when the element's .val() function is called. That is because those values consist of only an id and Select2 needs the entire data object (partly so it can display the correct label).
If the Select2 control was displaying a static list, the initSelection function would be easy to write (and it seems like Select2 could supply it for you). In that case, the initSelection function would just have to look up the id in the data list and return the corresponding data object. (I say "return" here, but it doesn't really return the data object; it passes it to a callback function.)
In your case, you probably don't need to supply the initSelection function since your element does not have an initial value (in the html) and you are not going to call its .val() method. Just keep using the .select2('data', ...) method to set values programmatically.
If you were to supply an initSelection function for an autocomplete (that uses ajax), it would probably need to make an ajax call to build the data object.
To set initial values you need to add the necessary options tag to the select element with jQuery, then define these options as selected with select2's val method and finally trigger select2's 'change' event.
1.-$('#selectElement').append('<option value=someID>optionText</option>');
2.-$('#selectElement').select2('val', someID, true);
The third boolean argument tells select2 to trigger the change event.
For more info, see https://github.com/select2/select2/issues/3057
Be carreful, there is a mistake in "validated" comment.
autocompleteInput.select2('data', {id:103, label:'ENABLED_FROM_JS'});
The correct way is
autocompleteInput.select2('data', {id:103, text:'ENABLED_FROM_JS'});
Use text instead of label
With Select2 version 4+, there is actually nothing special you need to do. Standard jQuery with a 'change' event trigger at the end will work.
var $select = $("#field");
var items = {id: 1, text: "Name"}; // From AJAX etc
var data = $select.val() || []; // If you want to merge with existing
$(items).each(function () {
if(!$select.find("option[value='" + this.id + "']").length) {
$select.append(new Option(this.text, this.id, true, true));
}
data.push(this.id);
});
$select.val(data).trigger('change'); // Standard event notifies select2
There is a basic example in the Select2 documentation:
https://select2.org/programmatic-control/add-select-clear-items
from their examples
https://select2.github.io/examples.html
Programmatic access:
var $example = $(".js-example-programmatic").select2();
var $exampleMulti = $(".js-example-programmatic-multi").select2();
$(".js-programmatic-set-val").on("click", function () { $example.val("CA").trigger("change"); });
$(".js-programmatic-open").on("click", function () { $example.select2("open"); });
$(".js-programmatic-close").on("click", function () { $example.select2("close"); });
$(".js-programmatic-init").on("click", function () { $example.select2(); });
$(".js-programmatic-destroy").on("click", function () { $example.select2("destroy"); });
$(".js-programmatic-multi-set-val").on("click", function () { $exampleMulti.val(["CA", "AL"]).trigger("change"); });
$(".js-programmatic-multi-clear").on("click", function () { $exampleMulti.val(null).trigger("change"); });
All you have to do is set the value and then execute: $ ('#myselect').select2 (); or $ ('select').select2 ();.
And everything is updated very well.
If you remove the .trigger('change') from your fiddle it logs Object {id: 1, label: "NEW VALUE"} (need to click twice since the logging is before the value change). Is that what you're looking for?
When using select2 with multiple option, use this construction:
$(element).select2("data", $(element).select2("data").concat(newObject), true);
jqueryselect2multiplesetconcatenation
this is it:
$("#tag").select2('data', { id:8, title: "Hello!"});
FOR VERSION 3.5.3
$(".select2").select2('data',{id:taskid,text:taskname}).trigger('change');
Based on John S' answer . Just the the above will work however only if while initializing the select2 the initSelection option is not initialized.
$(".select2").select2({
//some setup
})
For those still using version 3.5 or even higher ones. Please be sure how you reference select2.js to your page. If you are using async or defer load. This plug-in might behave differently.
Thought to mention.
In my situation I was able to render the preselected option into the HTML server side with PHP.
During my page load, I already knew the option value, so my <select name="team_search"></select> became the following;
<select name="team_search">
<?php echo !empty($preselected_team)
? '<option selected="selected" value="'. $preselected_team->ID .'">' . $preselected_team->team_name . '</option>'
: null ?>
</select>';
As you can see, when I have a $preselected_team available I render in an option with the selected attribute, value and label set. And, if I don't have a value then not option is rendered.
This approach may not always be possible (and in the case of the OP is not mentioned), but it does come with the added benefit of being ready on page load ahead of JavaScript execution.
Append a new option with id and text
let $newOption = $("<option selected='selected'></option>").val(1).text('New Text goes here');
$("#selector").append($newOption).trigger('change');
I have the following script which is working nicely to hide a DIV when its child is empty:
jQuery(".field-items").filter(function() {
return !$.trim(this.innerHTML);
}).parent().parent().parent().parent().parent().parent().hide();
If that same DIV is empty from above I also want to hide another DIV on the same page. It's not a parent.
How can I add the following code to the above code? So that both occur when that specific DIV is empty?
$('#survey-monkey-title').hide();
var $empty = jQuery(".field-items").filter(function() {
return !$.trim(this.innerHTML);
});
if ($empty.length) {
$empty.parent().parent().parent().parent().parent().parent().hide();
$('#survey-monkey-title').hide();
}
I'd also like to give Brian Giaz his propers for utilizing .add() below:
$empty.parent().parent().parent().parent().parent().parent().add('#survey-monkey-title').hide();
You can use the add() function to add additional elements to the jquery object:
$('#elem').parent().add('#otherElem').hide();
for example.
I know you already got it working, but consider updating the stringed parent() calls to just a single parentUntil function.
var $empty = jQuery(".field-items").filter(function() {
return !$.trim(this.innerHTML);
});
if ($empty.length) {
$empty.parentsUntil('.someSelector').hide();
$('#survey-monkey-title').hide();
}
I have the following code
$(document).ready(function () {
$(".page").on('click', function () {
$("#ctl00_MainContent_dfComments").html(function (i, val) {
return val.replace(/\]/g, '>');
});
});
$(".page").on('click', function () {
$("#ctl00_MainContent_dfComments").text(function (i, val) {
return val.replace(/\[/g, "<");
});
});
});
Which with the help of replacing characters in entire document JQuery works wonderfully. However, when the < bracket is inserted, the entire div goes blank. I can replace the [ with anything, but as soon as I put in < everything inside that div disappears. Any idea of what might be going on?
Yes, this is supposed to create a bold (kind of like a bb parser)
Your second replace is using .text() instead of .html(). As a side note, you can also combine the two event handlers.
$(document).ready(function () {
$(".page").on('click', function () {
$("#ctl00_MainContent_dfComments").html(function (i, val) {
return val.replace(/\]/g, '>').replace(/\[/g, '<');
});
});
});
Here it is in action: http://jsfiddle.net/pbnDP/8/
Pressing the button makes the text go bold.
The obvious security concerns are discussed in the comments on the main post. Don't put this on a site where users can generate the content this is being run on.
It looks like your probably not ending up with Valid HTML and the DOM rendering the html is disposing of any invalid HTML for you.
Theres a few problems with your script - the first it that it promotes dangerous html, your appear not to be doing any form of sanity or blacklist/whitelist checking on the code.
The other issue is your manually naming ASP.NET IDs - this is bad since they can change. Use .ClientID instead.
$(".page").on('click', function () {
$("#ctl00_MainContent_dfComments").html(function (i, val) {
return val.replace(/\[/g, "<");
});
});
.html might work better then text, and also use class name or clientid to select elements with like John suggested in his answer , that is not good to guess what the browser is going to change the id to.
Pleas check your DOM again, seems like browser either detects the < > as html tag or html aint valid.
Working version: http://jsfiddle.net/pbnDP/
I do know in few programming world including Ruby there is somthing called html_safe you might want to use alongside this.
Hope it helps.
So I am using jQuery to load in an html file then do a simple string replace on some tokens. However they will not do the replace. Can someone explain to me why this is not working with the replace calls?
pendingRow.html
<span id="{pendingDbId}" data-database="{pendingName}">
{pendingName} ({pendingTime}) - <a id="cancel-{pendingDbId}" data-dbId="{pendingDbId}" href="#">Cancel</a>
<br />
</span>
jQuery
$('#pendingLoadDiv').load('templates/pendingRow.html', function() {
$('#pendingLoadDiv').html($('#pendingLoadDiv').html().replace("{pendingName}", $('#database option:selected').text()));
$('#pendingLoadDiv').html($('#pendingLoadDiv').html().replace("{pendingDbId}", $('#database').val()));
$('#pendingLoadDiv').html($('#pendingLoadDiv').html().replace("{pendingTime}", "--:--:--"));
$('#pendingDiv').append($('#pendingLoadDiv').html());
});
It is getting all the way to the append at the bottom with no errors however it is not replacing any text.
I have even tried storing the pendingLoadDiv to a variable then running the replace calls on the variable and still am having the same issue.
Any ideas?
You really should not use load, I am sure the browser freaks out with the invalid characters in the id. Plus you are doing all of this DOM look ups when you can just work with the string directly.
$.ajax({
url: "templates/pendingRow.html",
success: function( data ){
var html = data.replace("{pendingName}", $('#database option:selected').text())
.replace("{pendingDbId}", $('#database').val())
.replace("{pendingTime}", "--:--:--");
$('#pendingDiv').append( html );
}
});
In the load success handler it has not yet updated the container. You should first set the html into the container and then try to replace.
$('#pendingLoadDiv').load('templates/pendingRow.html', function(data) {
var $pendingLoadDiv = $('#pendingLoadDiv').html(data);
var markup = $pendingLoadDiv.html();
markup = markup.replace("{pendingName}", $('#database option:selected').text());
markup = markup.replace("{pendingDbId}", $('#database').val());
markup = markup.replace("{pendingTime}", "--:--:--");
$('#pendingDiv').append(markup);
});
.replace() will only replace the first instance of the string, then return. To do a replaceAll, use a regular expression with the global flag: http://jsfiddle.net/RwPuu/
$('#pendingLoadDiv').html($('#pendingLoadDiv').html().replace(/{pendingName}/g, "replacingString"));
EDIT: The jQuery API documentation also seems to state, contrary to the other answers, that the selected element's content is replaced, then the callback is run. http://api.jquery.com/load
I'd guess that at the time the inner function has been called, Jquery has not yet updated the contents of your div with the loaded data, so you're search/replacing the OLD data, which is about to get deleted.
Try
$('#pendingLoadDiv).load('templates/pendingRow.html', function(data) {
^^^^^--- the loaded data
data.replace("{pendingName}", $('#database option:selected').text()));
etc...
$('#pendingDiv').append(data);
}