jQuery each() rewritten? - javascript

I've written a plugin for some divs. textbox is the class of divs and deactivateTextBox() is the plugin.
I need to deactivate all text boxes on the page. Are the following two pieces of code both doing this? And is the second one more efficient?
Code:
$(".textbox").each(function(){
$(this).deactivateTextBox();
});
$(".textbox").deactivateTextBox();

Yes, they both do the same thing.
Yes, the second should be more efficient as the former gets all elements, passes the raw DOM element to the loop, and then re-wraps the element with the jQuery object.

Related

Best practice in finding a DOM element

I want to toggle(hide/show) an element when a button is being pressed. I have two ways as to implement this:
Find the element according to its class name, e.g $('.my-content')
Find the element according to its relevant DOM position towards the button, e.g. $('#my-button').parent().next().next().next()
However, none of the above seems to me very reliable since in case someone changes the HTML code, the above approaches should not work. Is there something more reliable I am missing?
If it's a specific element, supply it with an Id value and use that
to find it.
If it's a TYPE of element, use a class name.
Other than that, there's no real conventions. Just try and make sure that somebody reading your code understands what is going on.
A very good practice is to decouple HTML, CSS and JS.
When binding javascript to DOM elements you should use javascript selectors.
Basically classes with some custom prefix (like js-) which will be used only for javascript purposes (not css style).
So whenever the DOM tree structure or the CSS class names are changed, you can still have your working JS selector
HTML
<div class="my-content js-toggle-element"></div>
JS
$('.js-toggle-element')
CSS
.my-content{ ... }
Plus, using Javascript Selectors:
makes HTML highly readable: you can easily find out what will happen to that element with that js class
allows you to easily apply/disapply that behaviour also to other elements in the future, simply by adding/removing that class in your HTML and without affecting CSS at all
<div class="my-content js-toggle-element"></div>
...
<div class="another-content-to-toggle js-toggle-element"></div>
Using jQuery will be much easiest way. Like this -
$( ".target" ).toggle();
The matched elements will be revealed or hidden immediately, with no animation, by changing the CSS display property. If the element is initially displayed, it will be hidden; if hidden, it will be shown.
Reference - jQuery Toggle
If the class or the position of the element in DOM is changing then you can try
selecting it with the inner text
$("button:contains('buttontextgoeshere')")

Initialize multiple js controls by searching DOM only once

I would like a function that initializes all of my javascript/jquery controls (date pickers, sliders...).
This is mostly done using a class attribute to identify on which element to initialize the control.
Currently, I'm using a jQuery selector to get the elements.
If I understand correctly, every time I use a selector I'm searching the whole page. So if I have 10 controls and one selector for each control type, I will search the whole page 10 times.
Could there be a way to search the page only once ?
The idea would be to have a collection of css class names with the corresponding initialization method to call. Go through the page only once, and on each element if I find a corresponding class, call the initialization.
Hope I'm being clear enough.
hope this helps. The approach I would suggest would be to apply a class to every item that you want initialized, lets say "initializeMe" and then have specific classes for datepicker etc.
$(function(){
$(".initializeMe").each(function(){
if($(this).hasClass("className")){
// lets say the class name is datepicker and you initialize datepicker here.
}
});
});
Could you give each one of those elements the same class and use the .each() method?
For example:
$('.canInitialize').each(function(){
Initialize($(this));
});
I don't know whether that prevents the DOM search every time or not.

How can I reuse this function?

I've wrote a function which is working fine and all but when I try to reuse it on multiple html blocks with the same class, it breaks. I've tried to use the .next() and .closest() method but without results. Where do I apply these? The function is to recreate a <select> dropdown but by using a unordered list.
It is important that the classes and function stay the same as the list is generated by the CMS and can be multiple times a page, so having a solution where I change the code and call each function separate is not good..
Demos
Dropdown works fine (function works fine on one unordered list)
Dropdown breaks (when reusing function and html code)
Your script had a number of things that needed changing. This should work, as best as I could understand what you were trying to do.
Main point being this:
$(".cloned").click(function(){
$('.options').toggle();
e.preventDefault();
});
The $('.options') selector inside the handler selects all the elements with the options class, regardless of where you clicked in the document. That's why every dropdown was activating on a click.
You should only select the specific .options element for the click. There are many ways to do this, but this is what I did:
$(this).next('.options').toggle();
This can be better.. Check out this fiddle
using toggleClass()
Fiddle

JQuery remove images

I'm curious if anyone knows why this piece of jQuery code doesn't remove the images?
var a = $('#tblMain').clone().remove('img');
The table is being selected. This is trying to take the table on the webpage and export to excel but I do not want the images to export.
Thank you,
Do it like this:
$("#tblMain").clone().find("img").remove();
EDIT: Okay, here's the problem:
selector: A selector expression that
filters the set of matched elements to
be removed.
http://api.jquery.com/remove/
The img in .remove('img') is to filter the set of items in the jquery object, NOT to find elements within the items themselves. In this case, the jquery object contains only one item, the cloned table. Therefore, .remove('img') removes nothing, since the jquery object does not contain any images (only images within items it contains).
I don't know what's happening behind the scenes, but you're referring to some variable called img whilst you most probably just want to select all img elements. In that case, you ought to use a selector as a string:
var a = $('#tblMain').clone().remove('img');
EDIT: .clone.remove does not seem to work indeed. I used this workaround which actually works:
.find('img').each(function() {$(this).remove()});

How to iterate a gridview by javascript

Suppose my gridview has a few rows and every row has a few textboxes. I want to iterate the gridview with JavaScript to read the value of each textbox. How easily can I achieve it by plain JavaScript or jQuery? I want a cross browser solution.
Definitely use jQuery. I use a couple of different jQuery selectors below. This should give you a general idea of how to accomplish your goal.
$('#gridviewId').find('.textClass').each(function () { alert($(this).val()) });
The above code would use the grid view's id and then would find all of the descendant elements with a particular class (in your case textboxes) alerting their value. I've added a working example at: http://jsfiddle.net/GWAAC/.
use jQuery. If you know the class or ID of the elements you need, a simple selector will return all of them

Categories

Resources