array push function not working on google chrome - javascript

I want to fetch multiple checkboxes values from one div. My code executes successfully on firefox but in other browsers it doesn't work. My code looks like
var amenity_array = [];
var listofParameters = $("#room-amenity input:checkbox");
for (var index in listofParameters) {
if ($(listofParameters[index]).attr('checked')) {
var ste = $(listofParameters[index]).attr('value');
amenity_array.push(ste);
}
}
alert(amenity_array);
in the above code amenity_array alerts within the braces but out of this it doesn't work on chrome.

Couple of suggestions/bugs:
Make sure your selector is correct to select checkboxes
Use :checked to select only the checkboxes that are checked
Don't use for...in for looping over array
You can use each() to get the checked checkboxes and add them in your array
Make sure that at-least one checkbox is selected, otherwise the array will have no elements in it
Code:
var amenity_array = [];
$('#room-amenity input:checkbox:checked').each(function() {
amenity_array.push($(this).val());
});
console.log(amenity_array);

Related

How to sum elements dynamically added with Javascript?

I am adding table rows dynamically to a table using Javascript.
Is there a reason why items.length doesn't increase when I add a row?
I am also trying to sum the numbers contained in each row. But this doesn't work either. The dynamically added rows are completely ignored for some reason.
I am coming from jQuery where things like these used to work.
I am probably missing something really fundamental here. Thanks for any pointers.
document.addEventListener("DOMContentLoaded", function() {
var form = document.querySelector("#form");
var items = form.querySelectorAll(".item");
form.addEventListener("click", function(event) {
if (event.target.className == ".add_item") {
addFields(event);
}
});
function addFields(event) {
var item = document.createElement("template");
item.innerHTML = fields.trim();
items[items.length - 1].insertAdjacentElement("afterend", item.content.firstChild);
console.log(items.length);
event.preventDefault();
}
})
querySelector and querySelectorAll returns NodeList where as getElementsByClassName returns HTMLCollection.
The difference is, NodeList is a static copy but HTMLCollection is a live copy. So if element is modified, like in your case, a new row is added, HTMLCollection will work but NodeList will not.
So changing
var items = form.querySelectorAll(".item")
to
var items = form.getElementsByClassName("item")
might solve the problem.
Pointers
You cannot have a selector in getElementsByClassName. It expects a className, you cannot use composite selector like #form .item.
Reference:
Difference between HTMLCollection, NodeLists, and arrays of objects
You only query the items once here:
var items = form.querySelectorAll(".item");
form.addEventListener(
//you call addItem here
)
function addItem(){
//you access items.length here
}
You need to keep re-query-ing the selectors every time you add an item.
var items = form.querySelectorAll(".item"); //i got queried for the 1st time
function addFields(event) {
items = form.querySelectorAll(".item"); //get items again
//...
}
Or just don't query outside addFields() all in all. Put var items = ... in the function. There's no need to put it outside.
Read up #Rajesh's answer why this is so.

List of checkboxes checked for specific classes

I would like to get a list of names of which checkboxes are checked in a specific DIV (page-wrap). I am creating a filter of sorts and have a treeview of different types like color, quality, grain, etc... Each has its own class assigned to them. Color has a class of color_cb, Quality is product_cb, Grain is grain_cb. The following code works great for any one of them but I'd like to test for all 3. Is there a way to modify this for all 3.
var selected = [];
$('#page-wrap input:checkbox.color_cb:checked').each(function() {
selected.push($(this).attr('name'));
});
alert(selected.join(","));
I've tried this but it doesn't work.
var selected = [];
$('#page-wrap input:checkbox.color_cb:checked input:checkbox.product_cb:checked').each(function() {
selected.push($(this).attr('name'));
});
alert(selected.join(","));
use comma separator b/w selected element
$('#page-wrap input:checkbox.color_cb:checked ,#page-wrap input:checkbox.product_cb:checked')
^^^^-- add , seperator
or use map()
var selected = $('#page-wrap input:checkbox.color_cb:checked ,#page-wrap input:checkbox.product_cb:checked').map(function () {
return $(this).attr('name');
}).get();
'#page-wrap input:checkbox.color_cb:checked input:checkbox.product_cb:checked'
this query selector means that input:checkbox.product_cb:checked is child of input:checkbox.color_cb:checked
But, i think you are looking for elements that accomplish one OR the other query, for that you have to use a comma separator, like this:
'#page-wrap input:checkbox.color_cb:checked, #page-wrap input:checkbox.product_cb:checked'
Simply removing the class should work fine.
var selected = [];
$('#page-wrap input:checkbox:checked').each(function() {
selected.push($(this).attr('name'));
});
alert(selected.join(","));
http://jsfiddle.net/60hnvnh9/1/
If there are checkboxes that you want to avoid targeting, simply give the checkboxes another, common class, and target that.

isolating specific values in external .js array

I'm currently trying to populate a selection list from an external javascript array. It works but I'm trying to populate only certain values using an ID column, which is failing. I'm using check-boxes and an 'If' statement to see which box is checked, and populate the appropriate array values based on this selection. I'm then using another 'If' within a for loop to match the ID value in the array, and add the matching values to the selection. However, it seems that it is completely disregarding the condition and reading the entire array in to selection list. It could be an obvious mistake with my code as I am only a novice.
function populateIslandList () {
var form = document.forms["island_form"];
var islands = form.islands;
if (islands[0].checked){alert("works");
for (i = 0; i < pislands.length; i++)
if (pislands[i][1] = 1){
document.forms["location"].islands.options[i] =
new Option(pislands[i][0], i)}};
if (islands[1].checked){alert("works");
for (i = 0; i < pislands.length; i++)
if (pislands[i][1] = 2){
document.forms["location"].islands.options[i] =
new Option(pislands[i][0], i)}};
}
Your first mistake is here:
var islands = document.getElementById("island_form");
document.getElementById() returns a single DOM element, not a list of objects. So, thus islands[0] and islands[1] are going to be undefined and islands[0].checked will make a script error.
You can only have one DOM element with a given id. You can have multiple elements with a class name so maybe you should switch to using class names and be using document.getElementsByClassName("something")
FYI, you should be looking in the browser error console or debug console to see script errors as this should have given you an indication of some trouble here.

Prevent double entry of tags in search by tags box

I'm trying to prevent double entry of tags in a tag input box that I've made.
Check it out:
http://jsfiddle.net/Newtt/4K6f7/5/
I'm trying to use two arrays to keep a check on which value is inside the box and which is inside drop down as such:
var array1 = ['PDF', 'Documents'];
var array2 = [];
where on click of an item from the drop down, it is removed from the array1 and put into array2. I'm not quite clear on the logic of it but I've tried my best to explain it in the fiddle.
The rest of the code is pretty straightforward for adding tags to the input box.
Is there a better way to do such a thing? If so, how?
Thanks!
Here is a quick fix:
if(array2.indexOf(c) == -1) {
array2.push(c);
if (d != '') {
...
}
and
$('#reset').click(function () {
array2 = [];
....
Each time you add an item, you push it also to array2.
Then you test (indexOf) if the item is already in that array before adding it twice.
Fiddle

How to hide multiple elements

I want to hide multiple elements when I press a button which get the value of checkboxs, and if the checkbox is checked it's hide.
I have the next code, but it just work with the first element
var checkedInputs = $("input:checked");
var test = "";
$.each(checkedInputs, function(i, val) {
test += val.value+",";
});
test = test.substring(0,(test.length-1));
$("#numRow"+test).hide('slow'); // it should to hide multiple elements, but just work with the first value
I also tried with array, but it doen't work too.
var numMsj =[1, 2, 4, 22, 44,90, 100];
$.each(numMsg, function (ind, elem) {
$("#numRow"+elem).hide('slow');
});
The modified solution
You could just put the hide inside the each loop:
var checkedInputs = $("input:checked");
$.each(checkedInputs, function(i, val) {
test += val.value+",";
$(this).hide('slow');
});
Here is a working example
The one-liner
Or if you don't need the test variable at all, you can do it is a single line:
$("input:checked").hide('slow');
Here is an example on that
The problem with your attempts
Just for reference, the reason your first example doesn't work is because your selector ends up looking like this:
$("#numRow1,2,4")
Which will select the first element with id numRow1, and then tags called 2 and 4, which won't exist. You would want to create your selector to look like the following:
$("#numRow1,#numRow2,#numRow4")
However, this is just an example, my alternative methods above are a much better approach.
The problem with your second attempt is simply a typo between numMsj and numMsg.

Categories

Resources