Does jQuery have a collect method - javascript

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.

Related

jQuery getting value from dynamic array

I have an array with divs ids (in my case its all divs ID values od parent div (#area) ):
jQuery.fn.getIdArray = function () {
var ret = [];
$('[id]', this).each(function () {
ret.push(this.id);
});
return ret;
};
var array = $("#area").getIdArray();
I need to get an array field value, something like this:
var lef = $("#array".[0]).css("left");
Taking a wild swing at it (see my comment on the question):
var array = $("#area").getIdArray();
var lef=$("#" + array[0]).css("left");
That assumes that getIdArray returns an array of strings, where each string is an id value for a DOM element, and that you want to get the left value for the first of those elements.
So for instance, if the array comes back as:
["foo", "bar", "charlie"]
then the selector created by "#" + array[0] is #foo, so you end up getting the left value for the foo element.
If you have an actual JS array within your variable array just use bracket notation to access each individual ID.
// I have the # before-hand since I'm assuming you have just the ID name
var lef = $('#' + array[0]) // this will access the 1st one in the array
I think you are looking for this :
var divYouWantToChange = $("#"+array[0]);
I try to formulate this as an answer because getIdArray is not a jquery function and we don't know what it does. If you'd like to apply a custom filter to the $("#area") collection you can do so using filter. This will return a jquery object where you can get the .css("left") from.
If you'd like to save both the id's and the left property you can do so with the following code:
var objects=[];
$("#area").filter(function(){
$this=$(this);//cache the object
objects.push({id:$this.attr("id"),
left:$this.css("left")
};
});
console.log(objects);

jquery - add to array

Why this not working?
var inputs = new Array();
$("input").each(function(){
input = $(this).val();
})
console.log(input);
how to correctly use arrays in jQuery? Like as PHP?
I assume what you are trying to do is get an array of the values of all the <input> elements on your page. What you'll need to do is iterate over all the elements using the .each() function and append each value to your inputs array.
Try this -
var inputs = new Array();
$("input").each(function(){
inputs.push($(this).val());
})
console.log(inputs);
You need to use the push() function to add an element to an array.
fiddle demo
References -
Array push method on MDN
As a final note, here is a shorthand way to define a new array -
var inputs = [];
That line is functionally identical to -
var inputs = new Array();
Use Array.push
var inputs = new Array();
$("input").each(function(){
inputs.push($(this).val());
})
Also note the variable differences .. input != inputs

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...

Updating a Drop down list with Jquery from JSON

I have a list that I need to fill using a JSON collection of object. Here is what my action is returning:
public ActionResult GetProductCategories()
{
var categories = _entities.ProductCategories.ToList();
var result = new List<SelectListItem>();
foreach (var category in categories)
{
result.Add(new SelectListItem {Text = category.CategoryName, Value = category.CategoryId.ToString()});
}
return Json(result, JsonRequestBehavior.AllowGet);
}
This is what I've come up with for my javascript, gathered from various sources:
function loadCategories() {
$.getJSON("/Admin/Product/GetProductCategories", null, function (data) {
var selectList = $("#subCategories");
$.each(data, function(index, optionData)
{
var option = new Option(optionData.Text, optionData.Value);
selectList.add(option, null);
});
});
}
But it doesn't appear to be working, and isn't giving any errors. Whats the best practice for this sort of thing?
I was wondering what are you trying to achieve in this next lines of codes,
var option = new Option(optionData.Text, optionData.Value);
selectList.add(option, null);
are you trying to create an option then add it on select? if so, do it like this, use .append()
selectList.append(option);
with that, I'm still assuming new Option(optionData.Text, optionData.Value); is creating a new option, in jQuery it would be like this var option = $('<option>').text(optionData.Text).val(optionData.Value);
added notes for .add(),
var selectList = $("#subCategories"); // creates jQuery object selectList.
selectList.add(option, null); // selectList is jQuery object,
// so when you call .add(), you're calling jQuery's `add()`.
a workaround is this,
selectList[0].add(option, null); // you can use [0] to convert it into DOM object.
difference between:
DOM select object's .add()
jQuery object's .add()
JQuery fails silently if it doesn't like the JSON data coming back from the server. Point your browser at /Admin/Product/GetProductCategories and look at the result. Make sure it doesn't have any html tags and make sure there are double quotes around the key names.

Buildling an array of vaules from page elements in JQuery/Javascript

I have a set of text boxes in which the user inputs an email address into each one. I want to loop around these and build an array of them. How do I do it?
var emailAddresses = new Array();
$(".email_address").each(
function() {
//add this $(this).val() emailAddresses
}
);
var emailsArr = $('.email_address').map(function(i,n) {
return n.value; //or $(n).val() or $(n).attr('value')
}).get();
See $.map for an awesomely concise way to do this sort of thing. get converts the returned collection into an array. Hope that helped.

Categories

Resources