How to check checkbox in each loop - javascript

Consider a simple each loop to inspect checked checkboxes:
$(':checkbox').filter(':checked').each(function(){
var name = $(this).val();
});
This code works for checkboxes checked in the original HTML code as
<input type="checkbox" name="test" value="test" checked="checked" />
How to make this jQuery code to work live, to perform the filter process every time a new box is checked or a checked is removed. I want to run the each loop upon any change in the checkbox (checked or unchecked) to return the updated values of currently checked ones.
NOTE: This is a simplified code to express the issue. The intention is not to record the name, but processing checked values in the each loop.

Use click:
$(':checkbox').click(function() {
$(':checkbox').filter(':checked').each(function() {
var name = this.value;
});
});
Notes:
You can avoid query the DOM so many times.
:checkbox is a very slow selector, because it's not a css selector but a jQuery extension.
Don't use jQuery to get this value.
You can improve your code like that:
var $checkboxes = $('input[type="checkbox"]');
$checkboxes.filter(':checked').each(function() {
var name = this.value;
});
Reading resources:
The cost of $(this)
Why we prefix our variables with $ in jQuery

You would need to bind your loop to the change event for the checkboxes.
$(':checkbox').change(function() {
$(':checkbox').filter(':checked').each(function() {
var name = $(this).val();
});
});

Since you're performing a loop, I'm assuming there can be many checked boxes. I'm a little confused why you would be overwriting the name variable each time though, leaving you only with the value of the last checkbox in the end. Instead, I'm providing an array which we push all checked values onto:
// Declare a names variable for storing values
var names;
// Any time a checkbox changes on our form
$("form").on("change", ":checkbox", function(e){
// Empty the names array
names = [];
// Get all checked checkboxes from our form and add their value to our array
$(":checkbox:checked", e.delegateTarget).each(function(){
names.push( $(this).val() );
});
}).find("input:checkbox").trigger("change");
// Method of revealing what we currently have checked
$("#reveal").on("click", function(){
alert( names.join(", ") );
});
Demo: http://jsbin.com/uyecux/2/edit

You need to create an event handler. In jQuery, this might look like this:
$(':checkbox').on('change', function() {
// Execute your code here.
});
See the jQuery documentation here: http://api.jquery.com/on/ for more details on event handling in jQuery.

var $checkboxes = $('input[type=checkbox]')
$checkboxes.click(function (){
$(':checkbox').filter(':checked').each(function(){
var name = $(this).val();
});
});
Try using above function.

Related

get checkbox name from javascript

I am trying to get a checkbox name when a checkbox is clicked...i am using a javascript function but it returns undefined.
Here is the code:
notType= document.getElementById($('[type="checkbox"]').attr('id')).value;
alert(notType);
In your code example, you are retrieving the value of the field, rather than the name. Instead, you should use:
var notType = document.getElementById(id).name;
you can do it like this:
$('input[type="checkbox"]').on('click', function(event){
alert(event.target.id);
});
This should work. $("#" + id) finds the element with the specified id. After that, you get the attribute called "name".
var notType = $("#" + id).attr("name");

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

How to get jquery selector seeing updated dom in change handler

I'm fairly new to javascript and jQuery. I've searched for answers to this question, but have had no luck, though I bet there are some in here. So advance apologies if this is a dup.
Markup has 3 checkboxes with different classes, and one class in common. I want to notice when the number of boxes checked in either of two classes changes, or rather when there is a transition between at least one box in two of the classes being checked or unchecked. The two interesting classes are named "professional" and "vendor", and the class in common is "account_type_checkbox".
When the page is ready, I count the number of checked "professional" and "vendor" boxes with:
jQuery("input.professional[checked='checked'], input.vendor[checked='checked']").length
This appears to work correctly. I have a "change" event handler on checkboxes in the common class that does the same count when it triggers. But when the event triggers, it gets the same count as it did on page load - i.e. it doesn't see the updated DOM with the modified checked attribute.
I've put a jsfiddle for this at http://jsfiddle.net/cm280s9z/1
Could someone please help me fix this, and/or explain why my code doesn't work the way I expected it to?
http://jsfiddle.net/cm280s9z/3/
Use alert($(":checkbox:checked").length); to get the sum of all marked checkboxes.
There are several other ways of doing this too, as pointed out in this thread, such as doing it by classes on a checkbox:
calculate the number of html checkbox checked using jquery
Maybe you will find this useful: http://jsfiddle.net/cm280s9z/6/
Here's a cleaned up version (not saying it's the best ever) of what you had, showing the :checked.
Reasons why this code is good:
storing the jQuery object checkboxes means it won't have to re-jquery-objectify it every time.
grabbing objects by certain [vague or lengthy] selectors can be more strenuous on jQuery. Grabbing by this class means it'll be more specific as well. We can further filter out checked using .filter. Extra Tip: If traversing the DOM, I like to grab a container that's fairly unique and use .find() to help me get at the descendants.
functions can bring some order and organization to what you're doing.
comments are your friend.
Hope this helps!
var GLOB = GLOB || {};
jQuery(document).ready(function () {
// Define
var checkboxes = jQuery('.account_type_checkbox');
var get_checkbox_count = function(checkboxes){
return checkboxes.filter(':checked').length;
};
var do_business = function(){
alert('transitioned to business');
};
var do_personal = function(){
alert('transitioned to personal');
};
// Initialize
GLOB.business_count = get_checkbox_count(checkboxes);
alert('GLOB.business_count = ' + GLOB.business_count);
// Events
checkboxes.change(function(){
var cur_count = get_checkbox_count(checkboxes);
var add_business = (cur_count > 0);
var no_business = (GLOB.business_count < 1);
// If any are selected it's business, where previously none were checked.
var transition_business = (add_business && no_business);
// If none are selected it's personal, if previously any were checked.
var transition_personal = (!add_business && !no_business)
if (transition_business)
do_business();
if (transition_personal)
do_personal();
});
});

Change textbox value in javascript

I want to update the value of text box from where I'm getting initial value to add product to cart.
Now I'm applying round function & I want to update the value of text box that is because I'm using ajax & if I'm applying round function, user must know how system calculated everything.
Here's my simple code:
<script>
$(document).ready(function(){
$(document).delegate('.purchasenow','click', function(e){
var buynow=this;
var productid = $(this).attr('id');
var quantity = $('.quo_'+productid).val();
var quantity = Math.round(quantity);
alert(quantity); //This gives the value
$('.quo_'+productid).value = quantity; //This is not working
});
});
Can anyone tell why it's not working? It's very simple but I'm not able to find out the cause.
Have you tried
$('.quo_'+productid).val(quantity);
The jQuery selector returns a wrapped object, not the actual DOM element. I don't think wrapped object has the .value property
you are almost correct the only thing why it is not working because your syntax is wrong
this is the correct syntax for jQuery
$('.quo_'+productid).val(quantity);
if you want it in javascript
var txt = document.getElementById("quo_"+productid);
txt.value = quantity;

Storing data in javascript for server side processing

The problem is simple. I have something like chessboard in HTML. The fields have coordinates, stored in ID attribute (ROW|COLUMN)
Clicking on a specific field makes it marked/unmarked. What is more, selected field's row and column are stored in a <input type="hidden"/> in the form of ROW|COLUMN,ROW|COLUMN,...
For every click I have to process the value of input hidden to check whether the field is already stored, add new field, remove existing and so on. It's a little awkward.
Are there any better ways? Or maybe it is the best way?:)
You don't have to store the fields state in an input field. Better use the a global JavaScript array or manipulate the DOM and serialize it's state before sending it to the server.
Here is some sample code in a JSFiddle: http://jsfiddle.net/U2D9Q/
The important part is where the className of the columns
$td.bind("click", function(e) {
$(this).toggleClass("selected");
});
and how it's serialized when you click the button
var serialize_table = function() {
var output = new Array();
$("table tbody").children().each(function(y) {
var row = new Array();
$(this).children().each(function(x) {
row[x] = $(this).get(0).className;
});
output[y] = row;
});
return output;
}
I used jQuery to keep the code clean. Feel free to use any JS Framework you like or write native JS.

Categories

Resources