How to hide multiple elements - javascript

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.

Related

array push function not working on google chrome

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

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.

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

Cloned row requesting same function [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
Call same function by a cloned list row
I am trying to make a simple calculation to work.
I have the following running:
http://jsfiddle.net/vSyK6/41/
Basically, the way it works now is this:
When you select an option on the drop down list it will display the content based on the option selected. Then when you select the same option again it will add, basically clone the same row.
Now, when the second option is selected "Option2" it will display an empty textbox. When you enter a number it will or should call the a function where we make a basic calculation. The function is already in the script.
However, when we have two empty textboxes it should call the same calculation function but calculate seperately and puts it in a different div. The div# where we display the amount is a called "amount"
Basically, it should work like this:
First Empty textbox -> 100 -> 100 * 22.38 = display result in div#1
Second Empty textbox -> 230 -> 230 * 22.38 = display in div#2
any idea on how to accomplish that ?
When cloning elements the id is cloned as well. It is best practice to create a new ID for the cloned elements, which will also help in accomplishing what you want. The same goes for the name attribute as well.
With a few modification to your code, http://jsfiddle.net/dNQVQ/3/, I was able to get what you were after. Let me first say that this might not be the ideal way to go, but it is a start. Like I said earlier the key is going to be setting unique ids for the cloned elements. What I did in this example was use a index as part of the list element id that is cloned with a matching index in an 'amount' div. This way when an input is updated the index is retrieved and then used to update the appropriate div. Additionally, I moved the function that did the calculation and updates to an anonymous function in the settimeout call. This makes it easy to use a reference to the updated input in the function call.
Joining the party quite late here :) Here is one vernon: http://jsfiddle.net/KVPwm/
ALso if its assignment bruv, put an assignment homework tag!
People around SO community are awesome folks so be truthful, guys will help man!
Use .on instead of live - recommendation. i.e. upgrade your JQ source if keen read this - What's wrong with the jQuery live method?
you have 2 document.ready functions also I chained few things for you.
Also think of using isNan check as well.
Rest you can read the code and play around a bit to make it more concise.
I have added 2 divs and using the id number to populate the stuff accordingly.
This should fit the cause :)
code
$("document").ready(function() {
/////////////////////////////////CALUCATIONS/////////////////////////////////
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 0; //time in ms, 5 second for example
$('input[name=Input2], input[name=Input1]').live('keyup', function() {
var str = $(this).prop("id");
var pattern = /[0-9]+/g;
var matches = str.match(pattern);
amount = parseFloat($(this).val()) * 22.38;
typingTimer = setTimeout(doneTyping(matches), doneTypingInterval);
});
$('#Input2').keydown(function() {
clearTimeout(typingTimer);
});
function doneTyping(matches) {
$('#amount'+matches).text(amount.toFixed(2) + " lbs");
}
$("#List-Option1,#List-Option2").hide();
$('#category').change(function() {
var str = $('#category').val();
if (str == 'Option1') {
var option1 = $("#List-Option1:first").clone().show();
$('#box li:last').after(option1);
}
if (str == 'Option2') {
var option2 = $("#List-Option2:first").clone().show();
$('#box li:last').after(option2);
}
});
});​

Javascript array not working as expected

I'm pretty new to js/jquery. For each checkbox with the ID of check$ (where $ is a sequential number), I want to toggle the class "agree" of the surrounding span that uses the same check$ (but as a class). I don't want to have to hard-code the list of matching checkboxes, as this may vary.
Here's my code. This function works as expected:
agree = function (checkbox, span) {
$(checkbox).change(function(){
$(span).toggleClass('agree');
});
};
This is what I'm trying to pass to the above function, which does not work:
$(function() {
var elemid = 'check',
checks = Array($('[id^='+elemid+']').length);
console.log(checks);
for (i=0; i < checks; i++) {
agree('#'+elemid+checks[i], "."+elemid+checks[i]);
}
});
console.log(checks) returns [undefined × 4]. The number of elements is correct, but I don't know why it's undefined, or whether that is even significant.
The following code works as expected, but as I say, I'd rather not have to specify every matched element:
$(function() {
var checks = ["check1", "check2", "check3", "check4"];
for (i=0; i < checks.length; i++) {
agree('#'+checks[i], "."+checks[i]);
}
});
Thanks.
Edit: Thanks to Jack, I was overlooking the most simple method. I added the same class to all checkboxes and spans, and solved the problem with this:
$('input.check').change(function(){
$(this).closest('span.check').toggleClass('agree');
});
I might be totally missing something, but I'm pretty sure you are just trying to attach a change handler to each checkbox. In this case you can give them all the same class. I'm also guessing at your html structure for the span.
For reference:
http://api.jquery.com/closest/
http://docs.jquery.com/Tutorials:How_jQuery_Works
$('.yourcheckboxclass').change(function(){ //grab all elements with this class and attach this change handler
$(this).closest('span').toggleClass('agree');
});
The reason that the array is full of undefined values, is that you are just getting the number of items in the jQuery object, and create an array with that size. The jQuery object is discarded.
Put the jQuery object in the variable instead:
var elemid = 'check', checks = $('[id^='+elemid+']');
checks.each(function(){
agree(this, "."+elemid+checks[i]);
});

Categories

Resources