Here is my old code:
checkboxes = document.getElementsByName('foo');
As you know, checkboxes will be an array. Now I need to limit selecting scope. So this is my new code:
checkboxes = $('.myclass input[name=foo]');
But in this case checkboxes isn't an array anymore, it's a jQuery object. How can I make it the same as getElementsByName('foo')'s result?
Note that $('.myclass input[name=foo]')[0] won't work either.
Try .toArray()
checkboxes = $('.myclass input[name=foo]').toArray();
Use this
var checked = [];
$.each($("input[name='foo']:checked"), function(){
checked.push($(this). val());
});
Charlie already pointed out that jQuery objects have a toArray() function. That would work I think. Figured it was also worth noting that there is also a .makeArray() function for generally converting array-like objects to native JavaScript arrays. https://api.jquery.com/jQuery.makeArray/
You can use .map() and create an array of underlying DOM which getElementsByName() returns
checkboxes = $('.myclass input[name=foo]').map(function(){ return this;}).get();
I would recommend #Charlie answer
You don't need to convert to Node elements array. Change your function to
function toggle(source, target) {
$(target).find('input[name=foo]').prop('checked', source.checked);
}
Usage
toggle(source, '.compare_people')
toggle(source, '.compare_posts')
document.querySelectorAll("input[name=foo]")
Getting javascript object from jquery object by $('selector')[0] should work. See the answer from this link How to get javascript control from JQuery object?
I suspect your selector is the reason why the above approach doesn't work. Add double quotes to name value will make it work:
checkboxes = $('.myclass input[name="foo"]');
Related
I get a lot of stuff moving about, and i was going to make a hashmap in javascript to allow me to remember certain things, one of which is objects recently touched. With that said, i was curious if i could create a key->value or array which hold the selector of the item clicked.
I wasnt sure if it was something like:
var item = new Array();
$("div.item").click(function(){
item.push($(this));
});
Then each item that is clicked is added to the array and i could do something like:
$(item).each(function(){
$(this).css("background-color","red");
});
Instead of using an array, you can use a jQuery object:
var $items = $();
$("div.item").click(function () {
$items = $items.add(this);
});
$items.css('background-color', 'red');
http://jsfiddle.net/b5qaT/
Make an empty jQuery collection and add to it.
var items = $([]);
$("div.item").click(function(){
var elem = $(this);
items = items.add(elem);
});
You want to pass the event as an argument in your eventhandler function. Like so:
$("div.item").click(function(e){...
e.whateverYouWantToDoWithIt;
The event is a javascript object, not jquery. You can google javascript event methods, attributes, etc. to see what you can do with it.
EDIT
Sorry, I read your question kind of fast. If you want to store the actual DOM object (the div) in the array, then yes, you would use the $(this) selector.
I have two selectors
var allNodes = $("a.historyEntry");
var errorNodes = $("a.historyEntry.error");
I would like to to find a node before first error node, so I need to find an index of first error node, how to do it?
I tried to use inArray method, but it doesn't work for this
$.inArray(allNodes, errorNodes.first())
or
$.inArray(allNodes, $(errorNodes.first()))
Is there any fast way to do it in jQuery or do I have to use for loop?
index()?
It's like indexOf... but just without the Of... it returns the index of the element if it exists, and -1 if it doesn't.
Use index(). It does exactly the same thing as indexOf in java.
$.inArray value is the first parameter then the array:
$.inArray(allNodes, errorNodes.first())
should be:
$.inArray(errorNodes.first(), allNodes)
Example
So I am not sure if my title is clear enough. I essentially have a div saved as a Javascript object which looks like this: [div#field_30.checkbox_group]
The field_30 is the ID which I am trying to extract here. doing something like object.id is not working. Does anyone know how to get the ID?
Note: I saved the object like this: var object = $(".workspace .selected"); which grabs the currently selected div inside the object called workspace. Sorry is this is a rookie mistake, I just can't seem to find anything anywhere. Thanks for the help...
var object = $(".workspace .selected"); will return a jQuery wrapped element that has jQuery properties and methods rather than element properties and methods. This means that any of
object[0].id
object.prop("id")
object.attr("id")
should work, but the 1st option should be the best performance-wise. It gets the id property of the the 1st element contained by the jQuery object, which is your div.
Your object is in fact a jQuery object, not a dom object.
To use the dom object use,
object[0].id
Or using, jquery, (Since it is already there)
object.prop('id');
You can use either $jquery_object.attr('id') or $jquery_object.eq(0).id
See this for exemple: http://jsfiddle.net/cquuT/
In this case it looks like object is the result of a jQuery select. To get to the actual DOM object you need to use [0]. Then you can access the id property
object[0].id
I don't see a complete answer here, so I'll provide my own.
If you're using jQuery selector $(), then you'll get jQuery-wrapped collection, not a single element.
(I assume now that you're using jQuery 1.5.2, the same as StackOverflow uses now.)
Universal solution to get ids of all elements returned by selector is:
.map(function(){ return this.id; })
Running $(".post-text").map(function(){ return this.id; }) on current page will return something like: ["", "", "", "", ""]
To get id of the first element returned by selector use:
.attr('id')
Running $("div").attr('id') on current page will return "notify-container".
Since jQuery 1.6 you can also use .prop('id') here.
If you know, that query will return only one element or you just want the first element matching given selector, then use .attr which is obviously a simpler solution.
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.
Is there a way in java script to get only a particular name instead of using document.getElementsByName("x"); which return an array? I have a kind of special situation where i can’t use the id. Any suggestions please?
Thank You.
Just get the first element:
document.getElementsByName("x")[0];
Or for safety:
function getFirstElementByName(element_name) {
var elements = document.getElementsByName(element_name);
if (elements.length) {
return elements[0];
} else {
return undefined;
}
}
(BTW getElementsByName returns a collection, not an array.)
If you're looking for a single element, take the first one from the nodelist, for example:
var element = document.getElementsByName("x")[0];
You can test it out here.
Or use jQuery, so you don't have to bother with all the browser annoyance.
You just have to do this:
$("*[name='x']").first();
To get the first element with that name. If you know the element type than you can use it instead of "*". jQuery will make your life easier every time!