Initialize dynamically added select2 - javascript

I've added select2 dynamically, but it won't initialize. I tried with following code (found on stackoverflow itself) but it wont work, please check my fiddle for code. Suggest me what I missed in code.
Thanks in advance
Check this
function initializeSelect2(selectElementObj) {
selectElementObj.select2({
tags: true
});
}
$(".select-to-select2").each(function() {
initializeSelect2($(this));
});

Some issues with the example provided:
select2 was already being applied to all .select2 dropdowns without any options with this line: $('.select2').select2();
$(".select-to-select2").each does nothing, because there are no dropdowns with the class select-to-select2. (Also, there's no need for the each, you can just pass $(".select-to-select2") to initializeSelect2.)
The string being appended to wrapper was not valid HTML. That last "remove" link ought to be within the wrapping .row div.
ids must be unique to the page. After adding more of the same exact dropdowns, they had the same ID/names as previous ones, so this would cause unpredictable behavior (old dropdowns could lose their select2 and only the new ones would get it). E.g. you can't have more than one element with id="pgm_que_ans1", the next one has to be different.
in this call, initializeSelect2(wrapper), wrapper does not specify which dropdowns to apply select 2 on: , it's better to save the new HTML to a variable (e.g. var $newSelects('html here');, and once that is added to the DOM, pass only the .select2s within that to initializeSelect2, e.g. wrapper.append($newSelects); initializeSelect2($newSelects.find('.select2'))
Here's a demo with all that thrown together:
http://jsfiddle.net/qw3y821g/1/

Related

Assigning JQuery On Click Function in For Loop

I have a function that dynamically creates div elements based upon whatever input is given, and lets them choose certain items by clicking on each div. I have it so that if the div is clicked, a function (named checkToggle) is called that makes it looks like it is selected and adjusts some related variables. There is a checkbox in the div element that is toggled by this function (hence its name). Long story short, I had to jump through some hoops to get it to work, most of which I don't even remember. Please don't ask me about that.
The point of this question is this. I initially used the following JavaScript code to run the function when the checkbox was clicked. It was assigned by the main function, which created these div elements using a for loop.
document.getElementById(`${itemID}-checkbox`).onclick = function() {
checkToggle(`${itemID}-checkbox`);
};
This works, but I wanted to try to convert all of my onClick functions to JQuery. Here is the JQuery alternative I created.
$(`${itemID}-checkbox`).on(`click`, function() {
checkToggle(`${itemID}-checkbox`);
});
While the code itself seems to be fine, it does not work. It seems as if JQuery functions cannot be created like this in a for loop or something. It is applied after the element is created and put in its place, so I don't think it has anything to do with the element not being ready. I am also having the same issue with 2 other similar cases. Any idea as of why this isn't working?
Let me know if more information is needed and if so, what kind of information is needed.
You need to update the selector to Target HTML id using the # character. Simply prepend the character to the query:
$(`#${itemID}-checkbox`).on(`click`, function() { checkToggle(`${itemID}-checkbox`); });
It would also apply to DOM methods querySelector or querySelectorAll as well.
Hopefully that helps!

Can I rewrite Javascript without using 'this'?

I'm very new to JS and I'm having trouble getting this to work.
Here is my code
jQuery('ul.menu li').each(function() {
jQuery(this).removeClass('current-menu-item');
jQuery(this).removeClass('current_page_item');
});
jQuery(this).parents('li').addClass('current_page_item');
jQuery(this).parents('li').addClass('current-menu-item');
Now what this should be doing is remove the highlight from one link on a navigation menu, and highlighting the one thats been clicked (I have an AJAX implementation).
For some reason it isn't doing anything. I have a feeling it is due to 'this' is there another way of structuring this code so I can work out if the code is wrong, which I don't believe it to be, or because of 'this'?
EDIT:
Apologies, it seems I haven't given enough information. I'm using the Twenty Fourteen wordpress theme but I'm serving the pages with AJAX.
http://twentyfourteendemo.wordpress.com/
I have the code being applied globally (I have other code in the same place to toggle the navigation once clicked (on mobile) and that works fine)
I have the menu at the top (without any dropdowns, just links). I can't give a link as it's not external currently. Should my code be working to change this?
As a few people have commented "What is 'this'" I feel I've completely missed something.
You don't need loop each item to do a remove class one by one, this is more easy :
jQuery('ul.menu li').removeClass('current-menu-item').removeClass('current_page_item');
Or (it's the same) :
jQuery('ul.menu li').removeClass('current-menu-item current_page_item');
But I don't understand what is this 'this' :
jQuery(this).parents('li').addClass('current_page_item');
jQuery(this).parents('li').addClass('current-menu-item');
Do you mean :
jQuery('ul.menu li').addClass('current_page_item current-menu-item');
Or if you are on an event listener (like click, as #Daniel Sanchez feel on comment) you just need to do :
jQuery('ul.menu li').click(function(){
// Remove class on each item
jQuery('ul.menu li').removeClass('current-menu-item current_page_item');
// Add class for this one
jQuery(this).addClass('current_page_item current-menu-item');
})
It's not entirely clear what you are trying to do but the code can be simplified somewhat:
jQuery("ul.menu li a").click(function(){
jQuery('ul.menu li').removeClass('current-menu-item current_page_item');
jQuery(this).parent('li').addClass('current_page_item current-menu-item');
});
http://jsfiddle.net/re3hjzyf/
Yes, by replacing this with 'ul.menu li'.
So the code would be like this
jQuery('ul.menu li').each(function() {
jQuery('ul.menu li').removeClass('current-menu-item')
.removeClass('current_page_item');
});
// not sure what the following code is referencing too
// it is outside the bounds of .each() function.
jQuery(this).parents('li').addClass('current_page_item');
jQuery(this).parents('li').addClass('current-menu-item');
what is this
When working with JavaScript and many Object Oriented programming languages the this keyword is used to refer to the current context that the programmer is working with. You're currently referencing to the ul.menu li element so by using this you make a call to the element that is selected in the .each() function.
You can replace it by using the element selector that you used in the each() function.
jQuery('.current-menu-item').removeClass('current-menu-item');
jQuery('.current_page_item').removeClass('current_page_item');
Here I am making the assumption that only one item will ever have those classes as it would denote which menu item is currently selected. The best way to select it is then to search for the class you want to remove. (If those classes always go together, you could also remove both on the same line, although then you might want to consider whether you actually need both.
jQuery('ul.menu li').on("click", function() {
jQuery(this).addClass('current_page_item').addClass('current-menu-item');
}
You can only use "this" as an argument for the selector when "this" has a value (i.e : inside an each loop or inside on.
In this case I am using the on() function to apply the function which adds the class to any of the list items which gets clicked on.
Merging the two you would then end up with :
jQuery('ul.menu li').on("click", function() {
jQuery('.current-menu-item').removeClass('current-menu-item');
jQuery('.current_page_item').removeClass('current_page_item');
jQuery(this).addClass('current_page_item').addClass('current-menu-item');
}

How to use common js function for two divs containig elements of identical ids?

I have common jQuery function and two div tags. Both div tags have different names but both containing elements of identical ids now i want to use this common Jquery function for them both?
I have implemented common function but it's not working for both.
Here's link to my jsfiddle -jsfiddle.net/xS7zF/1/
In my jsfiddle there are two div tags namely example1 and example2 and both tags have elements of identical ids. Function is working fine for first div but not for second.
please help me to sort out this.
Yeah, under the hood, jQuery selection on an ID will use the Document.GetElementById() function implemented by the browser, which is really fast, but (i guess depending on the browser) will stop after it finds the first element, since ID's should be unique and no further searching is needed after the first one is found.
For instance, rename the divs with id="eb" to class="eb" and you can still target specific elements using $("#example1 .eb") and $("#example2 .eb")
UPDATE:
Using your new Fiddle I created this: http://jsfiddle.net/xS7zF/5/
I cleaned up a lot of code and hopefully you can see what I have done. I changed all elements that appear twice from id to class. Now, when you attach an event to an element using $(".classname").click(), it attaches to all the elements. In the handler function where you set HTML and do your show()/hide(), you don't target a specific element using it's ID, but you find it relative to the element that does the event. You can do this using parent(), parentsUntil(), next(), find(), etc. Check jQuery docs for all possibilities. So for instance, the change-handler attaches to all inputs with name=Assets. But instead of doing $("#b1").show(), I go to the parent of the specific input that fires using $(this).parent(). Then I find the element with a class=".b1", which it will only find the one that is next to this specific input and I set the HTML to just that element.
Since there is another input, the same actions happen when THAT input changes, but instead it finds IT's parent, and finds the element with class=".b1" that is next to IT. So both divs with input are contained since they act on elements relative to itself and not across the document.
For extra fun and to show you how flexible this way of programming is, here is a fiddle with the Javascript-code unchanged, but with the exact same question-div copied 8 times. No matter how many times you repeat this, the same code will act on as many divs as you create since everything works relative. http://jsfiddle.net/xS7zF/7/
Hopefully this helps, the rest is up to you!
ID's must be unique, you should not repeat them. You could replace id with class and in the jQuery function do (".ub").each() or manually referencing the object using eq(x). e.g. (".ub").eq(1).
You shouldn't assign same id's to different elements.
You CAN but you SHOULDN'T. Instead of giving the same id, use class
IDs must be unique, try fix this, change to classes.
You can try something like this:
$("div div:first-child")
instead of
$("#eb")
But depends of the rest of your page code. So, change to classes first and use
$(".eb")
when jQuery / javascript find the first ID it would ignore the rest, please read more about it
http://www.w3schools.com/tags/att_global_id.asp

Removing all options containing text from all select lists on a page load

I'm trying to come up with a javascript/jquery method that will allow me to remove all select list options containing a particular text pattern on page load.
So far I have:
$('select option:contains(\'foo\')')
Which returns me all the elements - how can I remove them? My initial thought was something along the lines of:
$('select option:contains(\'foo\')').each().remove();
But this throws an exception.
Am I approaching this incorrectly?
$("select option:contains('foo')").remove();
jQuery functions automatically work on all selected elements. No need to use each() here.

Recursive jQuery function to amend select option values

I have a form that I am trying to alter with jQuery. Basically, my form has two elements and I need to change the value of the first option in each of them. However, there is an "add more" option that uses AJAX to dynamically generate another element that also needs changed. This add more button can be clicked an unlimited amount of times.
Right now I have this:
$(document).ready(function(){
$("#myname-0-field option:first").val("None");
$("#myname-1-field option:first").val("None");
});
This works fine, but once the "add more" button is clicked, I have more elements called "#myname-2-field", "#myname-3-field", "#myname-4-field" etc. These obviously aren't affected by adding another line into my jQuery as the document has already loaded when they are added.
So the real question is, can someone point me in the right direction of writing a function that can react when the new element is added and change it. If possible, I'm also looking for the function to be aware and look for "#myname-X-field option:first" for tidyness.
use live() function
Then using each function set value
From the jQuery API look live function
Maybe you could add class to your element, so that finding particular element would be easier and it would not add event to other similar elements.
In the example I have a Li with class
$('li.myClass').live('click', function() {
$(this).val(); // this is the getter for clicked value
$(this).val("some_value_here"); // this is the setter for clicked value
});
Now you can add more elements (that has myClass class) and it will have a click event.
Btw. if you know that all elements are inside some container (div for example) then you can write more efficient jQuery using delegate.
$('#container_id').delegate('li.myClass', 'click', function () {
});
This is more efficient because it looks your new elements only under "containter" not from the whole DOM structure.

Categories