Split jQuery collection into an array of individual jQuery objects - javascript

I am wondering if there is a way to split a jQuery selector which contains a collection of elements into an array of selectors, one for each element. For example, I have:
fields = row.find('input');
which returns a selector containing multiple input elements. I know I can use
fields.eq(index).val()
to access individual values, but is there an easy way to construct or convert fields to an array of selectors so I can just use
fields[index].val()
Edit:
Yes I realize you can use .toArray(), but as has been pointed out below, that returns an array of DOM elements. Then you'd have to loop through to convert these to selectors - too much extra work.

How about a small plugin to do this for you?
$.fn.toJqArray = function(){
var arr = [];
$(this).each(function(){
arr.push($(this));
});
return arr;
};
var inputs = $('input').toJqArray();
var value = inputs[0].val();
Here's a fiddle with usage.

You can use both jQuery toArray() function or jQuery.makeArray() function.
Both of them will return an array of DOM elements.
The difference is that toArray function converts only jQuery result object to an array:
$("p").toArray(); // correct
$.makeArray is more multipurpose and complicated. It converts any array-like objects to a proper JS array.
For example,
var elems = document.getElementsByTagName("p");
actually returns array-like nodeList, but not an array.
You cannot do:
var elems = document.getElementsByTagName("div");
elems.reverse(); // error. reverse() is not part of nodeList
However, you can do
var elems = document.getElementsByTagName("div");
var arr = $.makeArray(elems);
arr.reverse(); // ok. arr is a JS array which has reverse() function
However, in case of converting jQuery selection result - there is no difference between them.
Take a look at the following code snippet which makes a jQuery selection, converts this jQuery object to two JS arrays in two different ways and works with non-jQuery DOM innerHTML property.
var pJquery = $("p");
var pArray1 = pJquery.toArray();
var pArray2 = $.makeArray(pJquery);
document.getElementById('output').innerHTML = pArray1[1].innerHTML;
document.getElementById('output').innerHTML += pArray2[2].innerHTML;
p
{
color: #FF0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>1</p>
<p>2</p>
<p>3</p>
<div id="output"></div>

IF you use pure javascript, you access to inputs by an array, but if you need with jQuery you can make a loop:
var arrFields = [];
fields.each(function() {
arrFields.push($(this).val());
});
console.log(arrFields);
good luck!

You can do this:
var $input = $("input");
var $$input = $input.map(function() {
return $(this);
}).get();
console.log($input instanceof Object); // true
console.log($input instanceof jQuery); // true
console.log($$input instanceof Array); // true
$input.eq(3).val("test");
$$input[3].val("test");
But this is absurd.

You could use jQuery .toArray():
var arr = fields.toArray();
console.log(arr[0].value)
You can't use .val() here, but .value will work fine.
A small example/proof of concept:
var fields = $('input').toArray();
$.each(fields, function(i, o) {
console.log(o.value + ' == ' + fields[i].value)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input name="a" value="a" />
<input name="b" value="b" />
<input name="c" value="c" />
<input name="d" value="d" />

Yes you could use .toArray()
var fieldsArray = [];
fieldsArray = fields.toArray();

Each html element, if it don't posess an id, isn't guarentee to have a unique selector.

Related

Using JQuery's .attr() When Selector Returns Multiple elements

I am trying to pull 2 pieces of data from each of several fields. All the fields have been given the same "name" so as to allow them to be referenced easily.
<input type="text" name="common_name" data-X='ABC'>
The first piece of data I am pulling is their values, which does seem to be working. My issue is when I try to use attr(). It just stops dead in the water at that point.
var length = $('[name=common_name]').size();
for(var i=0; i < length; i++){
var value = parseInt($('[name=common_name]').get(i).value); //doesn't kill the script
var dataX = $('[name=common_name]').get(i).attr('data-X'); //Script is killed here
}
Since I'm not having issues with using attr() in general when the selector is selecting the element based on an id, I would think the issue has to do with the fact that in this case multiple elements are being returned by jQuery. What I am confused by is that I thought that get(#) is supposed to grab a specific one…in which case I don't see what the problem would be. (After all, using get(#) DOES work when I use val()).
So…why doesn't attr() work here?
.get() returns a dom element reference which does not have the .attr() method, so you can use the .eq() method which will return a jQuery object
var length = $('[name=common_name]').size();
for (var i = 0; i < length; i++) {
var value = parseInt($('[name=common_name]').eq(i).val()); //doesn't kill the script
var dataX = $('[name=common_name]').eq(i).attr('data-X'); //Script is killed here
}
The correct way to iterate over an jQuery object collection is to use the .each() method where the callback will be invoked for each element in the jQuery collection
$('[name=common_name]').each(function () {
var $this = $(this);
var value = parseInt($this.val()); //or this.value
var dataX = $this.attr('data-X'); //or $this.data('X')
})
Suppose the html is like this
<input type="text" name="common_name" data-X='ABC'>
<input type="text" name="common_name" data-X='DEF'>
<input type="text" name="common_name" data-X='GHI'>
Now the script part
$('input[name="common_name"]').each(function() {
var el = $(this);
text_val = el.val();
data = el.attr('data-X');
console.log(text_val);
console.log(data);
});
attr is a jquery fn, should call by jquery object
use like this
$('[name=common_name]').attr('data-X')
so try
dataX = $($('[name=common_name]').get(i)).attr('data-X');

Create array of certain attribute from a list of elements using jQuery

Say I have some of divs.
<div data-id="1"></div>
<div data-id="2"></div>
<div data-id="3"></div>
<div data-id="4"></div>
Is there a way to get an array of the data-id attribute: ["1", "2", "3", "4"] without using .each?
You could use .map(): (example here)
var array = $('div[data-id]').map(function(){
return $(this).data('id');
}).get();
console.log(array);
Alternatively, using pure JS: (example here)
var elements = document.querySelectorAll('div[data-id]'),
array = [];
Array.prototype.forEach.call(elements, function(el){
array.push(parseInt(el.dataset.id, 10));
});
console.log(array);
...or using a regular for-loop: (example here)
var elements = document.querySelectorAll('div[data-id]'),
array = [],
i;
for (i = 0; i < elements.length; i += 1) {
array.push(parseInt(elements[i].dataset.id, 10));
}
console.log(array);
You could use a for loop and do it without JQuery even, in case you are looking for a more primitive solution, like:
var nodes = document.querySelectorAll('[data-id]');
for(var i=0;i<nodes.length;i++){
// do something here with nodes[i]
}
Or to optain an array directly from your query result you could also use Array.prototype.map.call:
var values = Array.prototype.map.call(nodes, function(e){ return e.dataset.id; });
var array=$('div[data-id]');//array will store all the div containing data-id in the order as it is appearing in your DOM.
so suppose you want to get 2nd div just do like this array[1].attr('id')

Selecting inside a DOM element

This is the html code
<div class="extra-sub-block sub-block-experience">
<h6 style="display:inline;" id="exp-pos-0" class="extra-sub-block-head sub-block-head-experience">CEO</h6>
</div>
<div class="extra-sub-block sub-block-experience">
<h6 style="display:inline;" id="exp-pos-1" class="extra-sub-block-head sub-block-head-experience">COO</h6>
</div>
There are several such similar structures. Now I try to extract the values from each block.
var temp=document.getElementsByClassName('sub-block-experience');
var result=$(temp[0]+"#exp-pos-0");
This throws an error. I followed selecting element inside another DOM
I also tried
var temp=document.getElementsByClassName('sub-block-experience');
var result=temp[0].find('h6');
This doesn't work as well. What am I doing wrong here. Help?
For extracting the values from all blocks, you can use .map() function as follows:
var results = $('.extra-sub-block-head').map(function(){
return $(this).text();
})
Demo
side note: Since id is unique in a document, you can directly access the element using id selector like var result= $("#exp-pos-0");instead of var result=$(temp[0]+"#exp-pos-0");
Try, var result=$(temp[0]).find('h6');
Even, in the documentation link that you gave in question, it shows that you should wrap your result from document.getElementById in $() to be applied with jQuery. What it does is, that it converts the native javascript object into a jquery object.
Demo
function testIt(){
var tags, index;
tags = document.getElementsByTagName('h6');
for (index = 0; index < inputs.length; ++index) {
//do something ...
}
}
If I am correct you are trying to get ceo and coo?.If that's the case then with jquery:
var x= $('.extra-sub-block h6');
//values are
$(x[O]).html();
$(x[1]).html();
You could also use plain javascript:
var result = document.querySelectorAll('.sub-block-experience h6');
Or if you like it separate:
var temp = document.querySelectorAll('.sub-block-experience');
var result = [];
for(var i = 0, elem; elem = temp[i]; i++) {
result = result.concat(elem.querySelectorAll('h6'));
}
But be aware of the browser compatability of querySelectorAll and querySelector.

Jquery array.push() not working

I have been trying to add variables from a dropdown into an array using Jquery array.push() function but for some odd reason it is not working. Following is the jsFiddle link:
http://jsfiddle.net/dKWnb/3/
JavaScript :
$("#test").live("click",function() {
var myarray = new Array();
myarray.push($("#drop").val());
alert(myarray);
});
HTML
<Select name=drop id=drop>
<option value=1>1</option>
<option value=2>2</option>
</select>
<input type=button name=test id=test value=test>
Your HTML should include quotes for attributes : http://jsfiddle.net/dKWnb/4/
Not required when using a HTML5 doctype - thanks #bazmegakapa
You create the array each time and add a value to it ... its working as expected ?
Moving the array outside of the live() function works fine :
var myarray = []; // more efficient than new Array()
$("#test").live("click",function() {
myarray.push($("#drop").val());
alert(myarray);
});
http://jsfiddle.net/dKWnb/5/
Also note that in later versions of jQuery v1.7 -> the live() method is deprecated and replaced by the on() method.
Your code alerts the current value of the dropdown for me, showing that it has properly pushed into the array.
Are you wanting to keep old values and append? You're recreating the array each time, meaning that the old value gets clobbered.
Here's some updated code:
var myarray = [];
$("#test").click(function() {
myarray.push($("#drop").val());
alert(myarray);
});
jsFiddle
another workaround:
var myarray = [];
$("#test").click(function() {
myarray[index]=$("#drop").val();
alert(myarray);
});
i wanted to add all checked checkbox to array. so example, if .each is used:
var vpp = [];
var incr=0;
$('.prsn').each(function(idx) {
if (this.checked) {
var p=$('.pp').eq(idx).val();
vpp[incr]=(p);
incr++;
}
});
//do what ever with vpp array;
var array = [];
var element = "anything you want in the array";
array.push(element); // array = [ "anything you want in the array" ]

How can I get values from a list (not having items ids) with jQuery?

So I have a list with lots of items like below:
<ul id="usersList">
<li><FORM><INPUT class="eButton" type="button" value="robot669394444" onClick="openWin('robot669394444',1280,720)"></FORM></li>
<li><FORM><INPUT class="eButton" type="button" value="robot6693925" onClick="openWin('robot6693925',1280,720)"></FORM></li>
</ul>
I want to get all INPUT values using jQuery into an array. How to do such thing?
var vals = $("form input").map(function() {
return $(this).val();
});
Alternatively (more cleanly)
var vals = [];
$("form input").each(function() {
vals.push( $(this).val() );
});
The second alternative is more clean since it leaves you with a plain vanilla array. The result of map() still is a jQuery object. Since these are (and behave exactly like) arrays, this might not be a problem. But it's useful to keep that subtle difference in mind.
It's not always possible to store all params (keys and values) in an object, because two inputs can have same name.
But you can use: $('form.myform').serializeArray() to get an object like [{param1:value2}, {param2: value2}]
Or use
$('form.myform').serializeArray().map(function(e){ return e.value;})
to get list of all values [value1, value2, ...]
I am not sure of a way to do it with Jquery, but using simple javascript can help
var uL=document.getElementById("usersList");
var i=0;
var inArr=new Array();
while(uL.getElementsByTagName("FORM")[i]){
inArr.push(uL.getElementsByTagName("FORM")[i].getElementsByTagName('input')[0]);
alert(inArr[i].value);
i++;
}
inArr will contain all the input element objects in it...

Categories

Resources