Jquery array.push() not working - javascript

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" ]

Related

Get value of all dynamically created hidden fields with class?

I would like to get the values of dynamically created hidden fields with a class reference.
Example of created hidden field
<input class="SelectedClaimants" id="CodesList_2__Claimant" name="CodesList[2].Claimant" type="hidden" value="Jason Statham">
This is something along the lines of what i have tried.
$('.listSelected').on('DOMSubtreeModified', function (event) {
$(".SelectedClaimants").find('input[type=hidden]').each(function () {
var testC += $(this).val();
});
});
I was aiming to have them create into an array object, but at the moment i am happy just to get the values out into a concatenated string.
Try this (the result is logged to the console). It's based onn Tushar's answer, but the selector was wrong.
$('input[type="hidden"].SelectedClaimants').map(function () {
return $(this).val();
}).get().join(',')
You can use .querySelectorAll(), spread element, for..of loop. Note, id, e.g., CodesList_2__Claimant should be unique in document.
var testC = [];
for (let el of [...document.querySelectorAll("input[type='hidden'].SelectedClaimants")]) {
testC.push(el.value)
}

Split jQuery collection into an array of individual jQuery objects

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.

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');

How can I get a multiple selected values in dropdown

I am using drop down with multiple select name defined with select[]
How can I get selected values using jquery.
The same way as any form element - use val().
var selectedValues = $("#select").val();
With a multiple select you will see the value as a comma delimited string which can easily be posted for server-side processing or split into an array if required.
Example fiddle
If someone wants values with labels. Then here is the solution:
var hexvalues = [];
var labelvalues = [];
$('#myMultiSelect :selected').each(function(i, selectedElement) {
hexvalues[i] = $(selectedElement).val();
labelvalues[i] = $(selectedElement).text();
});
Try this,
Live Demo
$('#btn').click(function(){
$('#select option:selected').each(function(){
alert($(this).text());
});
})​
Try
var selectedItems= $('#ddlId option:selected');
selectedItems.each(function(obj,ind){
$(obj).val() ;
} // or do with for (var i=0// normal js loop
you should try this:
$("select[name^='select[']:eq(0)").val();
remember, that eq(0) is indicated what is the index of your element with the same name.

Does jQuery have a collect method

I have this code
var selected = new Array();
$(".client_associates_users input:checked").each(function(index) {
selected.push($(this).val());
});
and it works great but i was wondering if jQuery had a collect so i would not have to create an array and push to it.
I basically want all the values of the checked input fields
jQuery offers the .map() method,
var selected = $(".client_associates_users input:checked").map(function(index) {
return this.value;
}).get();
This method will create a new array out of whatever data you return from within the callback. Be aware that you need to call .get() at the end to get a real array.
Ref.: .map()
Yes, $.fn.map http://api.jquery.com/map/ or $.map http://api.jquery.com/jQuery.map/
var $checkboxes = $(".client_associates_users input:checked"),
selected = $checkboxes.map(function(i){
return $checkboxes.eq(i).val();
}).get();
or this for $.map (I prefer this one)
var $checkboxes = $(".client_associates_users input:checked"),
selected = $.map($checkboxes, function(el,i){
return $checkboxes.eq(i).val();
});
Update
No longer recreates a jQuery object on each iteration.
The jQuery object $(".client_associates_users input:checked") is an array so you should just be able to access those values if you append a .val() to the end of that selector.

Categories

Resources