Javascript does not recognize HTML arrays - javascript

How to pass this kind of HTML input to JavaScript so that it recognizes these array values?
<input type="checkbox" id="collection[]" value="0">
<input type="checkbox" id="collection[]" value="1">
<input type="checkbox" id="collection[]" value="2">]
The only idea I have (never played with js this way, tbh) is to reach it through:
$("#collection").val();
But I got undefined error. I have no other idea how to make javascript recognize that variable collection is an array and has to passed as such.
Thanks in advance!

Remember, IDs need to be unique within your document. So set by 'name' not by id.
You can use
$('#someid').is(":checked");
for individually checking each checkbox, or loop through them with a jQuery selector
To loop through them set
<input type="checkbox" name="checkboxes" value="0">
<input type="checkbox" name="checkboxes" value="1">
<input type="checkbox" name="checkboxes" value="2">
Then with jQuery,
$('input[name=checkboxes]:checked').each(function(i, e) {
e.val(); //The value of the checkbox that is selected
});

You cannot have Duplicate Ids. Though duplicate IDs will give you desired output in this case, it is invalid to use them for multiple elements.
<input type="checkbox" name="collection[]" value="0">
<input type="checkbox" name="collection[]" value="1">
<input type="checkbox" name="collection[]" value="2">
There are many ways you can access array based elements.
jQuery .map(): Alternative is .each()
Demo
$("[name='collection[]']").map(function(){return $(this).val();}).get()
Working Demo for checking checked inputs.
To get the checked checkbox,
$('input').change(function () {
console.log($("[name='collection[]']:checked").map(function () {
return $(this).val();
}).get());
});

$("#collection")
It mean's ,"Find me an element which id's equal collection on page" , of course it can't find anything. You can use .each function and you can use checkboxes attributes. For example ;
var myCheckBoxArray = []
$("input[type='checkbox']").each(function(i,elm){
myCheckBoxArray.push(elm);
});

Related

Is order of resulting array of document.querySelectorAll("input[type=checkbox") guaranteed?

I have the following HTML in the page body - these are the only input's of type checkbox on this HTML page:
<fieldset>
<legend>North Face</legend>
N-A1:
<input type="checkbox" name="NorthFace" value="N-A1" id="NA1">
N-B2:
<input type="checkbox" name="NorthFace" value="N-B2" id="NB2">
N-C3:
<input type="checkbox" name="NorthFace" value="N-C3" id="NC3">
N-D4:
<input type="checkbox" name="NorthFace" value="N-D4" id="ND4">
N-E5:
<input type="checkbox" name="NorthFace" value="N-E5" id="NE5">
N-F6:
<input type="checkbox" name="NorthFace" value="N-F6" id="NF6">
N-G7:
<input type="checkbox" name="NorthFace" value="N-G7" id="NG7">
N-H8:
<input type="checkbox" name="NorthFace" value="N-H8" id="NH8">
</fieldset>
<br />
<fieldset>
<legend>South Face</legend>
S-A1:
<input type="checkbox" name="SouthFace" value="S-A1" id="SA1">
S-B2:
<input type="checkbox" name="SouthFace" value="S-B2" id="SB2">
S-C3:
<input type="checkbox" name="SouthFace" value="S-C3" id="SC3">
S-D4:
<input type="checkbox" name="SouthFace" value="S-D4" id="SD4">
S-E5:
<input type="checkbox" name="SouthFace" value="S-E5" id="SE5">
S-F6:
<input type="checkbox" name="SouthFace" value="S-F6" id="SF6">
S-G7:
<input type="checkbox" name="SouthFace" value="S-G7" id="SG7">
S-H8:
<input type="checkbox" name="SouthFace" value="S-H8" id="SH8">
</fieldset>
I have a SUBMIT button on this HTML page that when clicked by the user runs some javascript that needs to evaluate these checkboxes - so I do the following:
var checkboxes = document.querySelectorAll("input[type=checkbox");
so far every time I have checked the array checkboxes indexes 0-7 of checkboxes are N-A1 through N-H8 and indexes 8-15 are S-A1 through S-H8.
Question 1: as long as these remain the only checkbox type on this HTML page and they are always in this order on the page is this order in checkboxes array always guaranteed? (that is will the first 8 always be N-xx and the second 8 always be S-xx?)
Question 2: if a checkbox get's added somewhere else on this HTML page I'm hosed so what would be the best way to get only this set of checkboxes? Put sometype of div with an id around these 2 fieldset's or put some type of id on each of these fieldsets like "north" and "south". Give quick example of how to fetch the checkboxes in this case.
Question 3: what I really want in the end is to send only the checkboxes that are checked to my PHP backend - currently I am using a for loop in javascript on checkboxes to find which boxes are checked in javascript then send those that are checked in the POST to my PHP code. Is there a better way - best way to do this maybe just sent the whole checkboxes array in the POST and process in PHP to find who's checked?
Thanks in advance for ideas/suggestions...
1
Yes, the order is guaranteed.
The specification states
The querySelectorAll() methods on the Document, DocumentFragment, and
Element interfaces must return a NodeList containing all of the
matching Element nodes within the subtrees of the context node, in
document order. If there are no matching nodes, the method must return
an empty NodeList.
meaning the elements will be returned in the order they appear in the document
2
If checkboxes are added, the best way to get those elements would be to keep track of them when inserting.
Other than that, wrapping them in another element with an ID or class would work as well, or just giving the new checkboxes a class
var new_boxes = document.querySelectorAll('.new_boxes');
3
Generally you'd just submit the form, and the checked boxes will be sent automatically.
If you're sending the data with ajax, you can get the checked boxes with an attribute selector
var boxes = document.querySelector('input[type="checkbox"][checked]');

Select dom elements by attributes having array like attributes

I have many elements that are structured to get them in array like mapping on server side.
<input type="CHECKBOX" id="478" value="1" name="data[GroupInfo][student][478]" onclick="return updateValues('478')">
<input type="CHECKBOX" id="490" value="1" name="data[GroupInfo][student][490]" onclick="return updateValues('490')">
<input type="CHECKBOX" id="478" value="1" name="data[ClassInfo][student][478]" onclick="return updateValues('478')">
<input type="CHECKBOX" id="490" value="1" name="data[ClassInfo][student][490]" onclick="return updateValues('490')">
so on...
Now, I want to select them using their name attribute like
$("[name^=data[ClassInfo][student]]");
but this won't work
I tried to escape barckets to.
$("[name^=data\[ClassInfo\]\[student\]]");
but no luck;
I want to select them using name attribute.
Just wrap the attribute value in ""
$('input[name^="data[ClassInfo][student]"]')
Demo: Fiddle
Try this:
$("[name^='data[ClassInfo][student]']");//Wrap in the single quotes
Try:
// For exact element
$('input[name=data[GroupInfo][student][478]]');
Or
// For list of elements
$('input[name^=data[GroupInfo][student]]');
You can see more here
$('input[name*="data[ClassInfo][student]"]') // matches those that contain 'data[ClassInfo][student]'

Building a dynamic if or statement in javascript for use as a filter

I'm looping through object keys in a firebase database then checking the property myFirebaseObject.category for a specific category. I have multiple filters that will be stacked. If a checkbox is checked I want to include all objects associated with that category and combine them with other selected categories in my new array.
I'm not necessarily looking for code unless it's the best way to explain your approach. I'm trying to learn so I'm thinking more conceptually: "What is the best approach to building stackable filters using checkboxes in javascript"
Is there a good way to dynamically build this if statement(assuming 1 and 3 were checked)?
If statement:
if (myFirebaseObject.category === '1' || myFirebaseObject.category === '3' && myFirebaseObject.enabled === '1'){//populate an array};
My checkboxes:
<input id="cat1" class="category_check" type="checkbox" checked="true" name="filter" value="1" >1<br>
<input id="cat2" class="category_check" type="checkbox" name="filter" value="2">2<br>
<input id="cat3" class="category_check" type="checkbox" checked="true" name="filter" value="3">3<br>
<input id="cat4" class="category_check" type="checkbox" name="filter" value="4">4<br>
Instead of dynamic IF statement, use an array. You can then check to see if the item is in the array easily.
See: JavaScript is in array

How to use .change() check on only part of a page

I have a bunch of html check boxes on a page, but want to have two different groups of checkboxes. I'm thinking that I can assign them into a class or insert them into a div, so that I can somehow refer to them separately...? Just unsure how to do this syntaxically.
For example, currently I'm using
$('input[type=checkbox]').change(function(){ /*insert my code functionality here*\ });
to refer to the checkboxes, but this changes all of my checkboxes, when I only want it to apply to half of them.
You may try this
HTML
<input type="checkbox" value="1" class="group1" name="chk1" />Check One
<input type="checkbox" value="2" class="group1" name="chk2" />Check Two
<input type="checkbox" value="3" class="group2" name="chk3" />Check One
<input type="checkbox" value="4" class="group2" name="chk4" />Check Two​
JS
$('input[type=checkbox].group1').change(function(){
// code
});
$('input[type=checkbox].group2').change(function(){
// code
});
An Example Here.
Use classes to separate them into two groups..
.tobechecked // Assign a class to all the checkboxes that need to
// for this event
$('.tobechecked').change(function(){
Identify the groups by diferent classes, then you can determine it by the class via jquery.
$('.specific_group_class').change(function(){..}
Like you said in your question, use classes.
Then you can do as such:
$(".check-1, .check-2").change(function(e) {
/* do work */
});
See jsFiddle

.checked=true not working with jquery $ function

i want to select a checkbox when a button is clicked.
<form action="" method="post" id="form2">
<input type="checkbox" id="checkone" value="one" name="one" />
<input type="button" value="Click me" id="buttonone"/>
</form>
when i tried the following, the checkbox was not getting selected
$('#buttonone').click(function() {
$('#checkone').checked=true;
});
then i tried:
$('#buttonone').click(function() {
document.getElementById('checkone').checked=true;
});
this time the checkbox got selected. why isn't it getting selected with the jquery $ function?
Try
$('#checkone').attr('checked', true);
or
$('#checkone').get(0).checked = true;
or
$('#checkone')[0].checked = true; // identical to second example
The reason your first code didn't work is because you were trying to set the checked property on a jQuery object which will have no visible effect as it only works on the native DOM object.
By calling get(0) or accessing the first item [0], we retrieve the native DOM element and can use it normally as in your second example. Alternatively, set the checked attribute using jQuery's attr function which should work too.
You need to use .attr() for the jQuery object, like this:
$('#buttonone').click(function() {
$('#checkone').attr('checked', true);
});
But it's better to do it the DOM way, like this:
$('#buttonone').click(function() {
$('#checkone')[0].checked = true; //get the DOM element, .checked is on that
});
Or, completely without jQuery:
document.getElementById('buttonone').onclick = function() {
document.getElementById('checkone').checked = true;
};
None of these answers worked for me because I incorrectly had multiple radios with the same name attributes:
<div id="group-one">
<input type="radio" name="groups" value="1" checked="checked" />
<input type="radio" name="groups" value="2" />
</div>
<div id="group-two">
<input type="radio" name="groups" value="1" checked="checked" />
<input type="radio" name="groups" value="2" />
</div>
Javascript won't recognize the checked attribute (obviously). This was a result of using include to add a similar section of HTML multiple times. Obviously, clicking on a radio button will uncheck the radio toggles with the same name.
Here's a jsfiddle to show that two radio elements can have the attribute checked but only the last one is actually checked:
http://jsfiddle.net/bozdoz/5ecq8/
Again, pretty obvious, but possibly something to watch out for: remove id and name attributes from files that you intend to include into other files multiple times.
Try
$('#checkone').attr('checked', true);
You don't have direct access to DOM object properties because jQuery operates on collections ($(selector) is an array). That's why you have functions defined to manipulate the contents of the returned elements.
try
$('#checkone').attr('checked', true);
cleary googling for "jquery check a checkbox" was the way to go
Or you could simply do
$('#buttonone').click(function() {
$('#checkone')[0].checked=true;
});
It is because ".checked" is not part of jQuery and you are trying to use it on a jQuery object. If you index a jQuery object at [0] you get the raw Javascript object which ".checked" exists on.
More here: http://phrappe.com/javascript/convert-a-jquery-object-to-raw-dom-object/
try this
$('#buttonone').click(function() {
$('#checkone').prop('checked', true);
});

Categories

Resources