jQuery Multiple ID selectors - javascript

Here's a snippet of the start of my code:
var myUpload = $("#upload_link").upload({bla bla bla
Basically what I'm trying to do is make the same call with a few different ID's...
I would have assumed this would work but it doesn't:
var myUpload = $("#upload_link,#upload_link2,#upload_link3").upload({
Any ideas?

Try this:
$("#upload_link,#upload_link2,#upload_link3").each(function(){
$(this).upload({
//whateveryouwant
});
});

If you give each of these instances a class you can use
$('.yourClass').upload()

You can use multiple id's the way you wrote:
$('#upload_link, #upload_link2, #upload_link3')
However, that doesn't mean that those ids exist within the DOM when you've executed your code. It also doesn't mean that upload is a legitimate function. It also doesn't mean that upload has been built in a way that allows for multiple elements in a selection.
upload is a custom jQuery plugin, so you'll have to show what's going on with upload for us to be able to help you.

Make sure upload plugin implements this.each in it so that it will execute the logic for all the matching elements. It should ideally work
$("#upload_link,#upload_link2,#upload_link3").upload(function(){ });

If all your elements starting with upload_ in its id have the same purpose or syntax you could try and use the following:
$("*[id^='upload_']").each(function() {
$(this).upload()
});
This way you don't have to specify every single element in the selector.

it should. Typically that's how you do multiple selectors. Otherwise it may not like you trying to assign the return values of three uploads to the same var.
I would suggest using .each or maybe push the returns to an array rather than assigning them to that value.

That should work, you may need a space after the commas.
Also, the function you call afterwards must support an array of objects, and not just a singleton object.

Related

How to store and reuse a combination of selector and context expressions in a single variable?

I've recently come to enjoy using this pattern of JQuery selector that I suppose you could describe as a syntactical shortcut for the .find() API:
$('.some-element', '.within-context')
There's a discussion about it on SO here
Anyway, I find myself in the situation where I'd like to store this selector as a variable that I can use in multiple places in my script.
Obviously I can't do this: var selector = '.some-element', '.within-context' as that would just leave me with a variable holding '.within-context'
'.some-element, .within-context' is something entirely different...
And despite sleuthing around the docs and SO, I'm not even sure what this does: $(['.some-element', '.within-context'])
Not really sure what else to try, should I just make two variables?
Consider using the spread operator to expand the $'s arguments from an array. This way you can store a selector combination in an array and pass it later on as two distinct arguments to the jQuery constructor.
For example:
let someSelectorCombo = ['.some-element', '.some-context']; // Store the selector
$(...someSelectorCombo).text('Yay') // Expand the stored selector to two arguments
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="some-context">
<div class="some-element"></div>
</div>
Why not just $('.within-context .some-element')?
Or if you still wanna use context, you can use apply, but I see not much point
var selectorWithContext = ['.some-element', '.within-context'];
$.apply(null, selectorWithContext);

simple way rather than to call a function repeatedly in javascript

I have a function and some input element(s) will use that for a purpose.
i tried to make an array of them and pass to that function, but failed.
$("#txtFirst").change(function(){validateForm($(this));});
$("#txtLast").change(function(){validateForm($(this));});
$("#txtNick").change(function(){validateForm($(this));});
how to make it more simple, rather than use same format repeatedly?
You can target multiple elements in one selector :
$("#txtFirst, #txtLast, #txtNick").change(function(){validateForm($(this));});
Try this:
$("#txtFirst, #txtLast, #txtNick").change(function(){validateForm($(this));});

Declaring a var instead of using .find multiple times?

I have been reading on best practices and I have come across this one:
Dont do this:
$("#element .child").hide()
Do this:
$("#element").find('.child').hide()
Now my question is what if i want to hide/show the .child element multiple times, should I declare it like this:
var spinner = $("#element").find('.child');
spinner.hide();
or do I just keep calling $("#element").find('.child').hide()
Should I declare it like this:
var spinner = $("#element").find('.child');
spinner.hide();
Yes. You should do exactly that since it will obviate the need for multiple dom queries.
One common best practice though, so you can easily keep track of which variables are jQuery objects and which are not, is to prefix your variable with $
var $spinner = $("#element").find('.child');
$spinner.hide();
Yes, create the spinner variable. That way the jQuery constructor/function won't be executed each time, you can reuse the once created objects. The memory overhead is negligible.
That's entirely depending of your problem, if you need to use the same element for multiples purposes in different function, the best options will be to save it into a variable, never the less if you only need once work with chaining of events
Yes, you should always try to keep your selections low, which means that you should save every element selection in a variable that you need more then once.
Try to avoid single DOM operations, also. Let me provide an example:
jQuery('#test').addClass('hide');
jQuery('#check').addClass('hide');
This will add the class "hide" to elements with the id "#test" or "#check". You can apply many jQuery functions like .addClass on element collections also, which will reduce overhead (instead for example iterating over an array / collection with jQuery.each()).
// Select both ids within one query
jQuery('#test, #check').addClass('hide');
This can lead to a huge performance boost if you are really working with the DOM, like adding options to a select box. I've put up a little benchmark on jsfiddle: http://jsfiddle.net/rrgNZ/2/

Control references in jQuery

function eegetdropdownvalue_str(ctl){return ctl.selectedIndex>=0&&ctl[ctl.selectedIndex]?ctl[ctl.selectedIndex].value:''}
The above function is called with
co.p1A10=eegetdropdownvalue_str(document.formc.p1A10);
I want to switch the call over to jQuery to drop the document.form reference however doing this
co.p1A10=eegetdropdownvalue_str($('p1A10'));
Does not reference the control correctly - How should I do this?
There's two things wrong with your code.
First, $('p1A10') references nothing.
jQuery selectors work almost identically (if not completely identically) to the way css works.
So, just ask yourself how you would reference the object(s) in question in CSS and you're half way there.
I'm assuming that p1A10 is the name or id of an object. Since we're using CSS/jQuery syntax, this should be an id, although you can select by other attributes such as $("select[name='p1A10']") .
To reference an object by ID we use the # character (again, just like in CSS). So we can select your node via $('#p1A10').
The second problem is that your function is expecting a DOM object not a jQuery object. To keep your code intact, we need to say $('#p1A10')[0] where 0 is the first element within the collection of jQuery elements.
I've provided two examples to explain this a little better. One uses your existing infrastructure and one replaces it.
http://jsfiddle.net/TD6Uu/5/
Hope it helps.
Given a form with id formc and a select with name p1A10 you could e.g. use:
o.p1A10 = eegetdropdownvalue_str($('#formc select[name="p1A10"]').get(0));
If this doesn't do it, please provide use with the exact HTML structure

Hiding multiple tag with same name or class

I have using prototype 1.5. Can you please tell me, how can i hide/show the div tag with same name or class.
Element.hide('indicate')
But, the above line only satisfy to hide the first element only. "indicate" is the id.
As pointed out, the $$ function is required. It returns an array so you need to invoke hide on all items.
$$('.indicate').invoke('hide');
Or, for bonus showing off points, you can use the function directly as an object:
var hideFunc = Element.hide;
$$('.indicate').each(hideFunc);
The advantage of this technique means you can easily swap the function for another, such as a Scriptaculous effect.
hideFunc = Effect.SwitchOff;
Having the same id for two elements isn't supported in HTML, so there's no methods in Javascript to handle it. No matter what framework you're using.
Prototype provides the $$() function which you can use to query any CSS selector.
So if you have multiple items with a single class, you can query them like this:
$$('.indicate');
See the Prototype manual: http://www.prototypejs.org/api/utility/dollar-dollar
By the way, since you're using Prototype 1.5, I could also mention that it gives you a .getElementsByClassName() function as well. However, this has now been deprecated in more recent versions since its functionality is already covered by $$(), and to avoid confusion, since modern browsers implement a native function with the same name, but different syntax.
So don't use it, but for the sake of completeness, here is the manual link: http://www.prototypejs.org/api/element/getElementsByClassName
ID's have to be unique. Select with a class instead.
$$('div.indicate').hide();
or with its name attribute
$$('div[name=indicate]').hide();

Categories