How to iterate through all checkboxes on the page? - javascript

How do I can iterate through all checkboxes on the page with JQuery?
I.e. I have those checkboxes above...
<div>
<input checked="checked" type="checkbox" name="option_1" id="checkbox_1" value="1" />35 MM
<input checked="checked" type="checkbox" name="option_2" id="checkbox_2" value="2" /> DIGITAL
<input type="checkbox" name="option_3" id="checkbox_3" value="3" /> 3D DIGITAL
</div>
Have I use
$('input[id^="checkbox_"]').each(function() {
});
Is it correct? Thank you!

$("input[type='checkbox']").each(function(){
var name = $(this).attr('name'); // grab name of original
var value = $(this).attr('value'); // grab value of original
var ischecked = $(this).is(":checked"); //check if checked
});

You can use this to iterate through the checkboxes:
$("input:checkbox").each(function() {
alert($(this).val());
});

jQuery supports a selector :checkbox that is just for selecting checkboxes on the page so if you want all checkboxes on the page that's the simplest way to do it:
$(":checkbox").each(function(index, element) {
// put your code here
});
In the jQuery doc for :checked, they recommend that this selector might perform slightly faster:
$("input[type='checkbox']").each(function(index, element) {
// put your code here
});

$('input[type="checkbox"]').each(function() {
...
});

It seem alright but you can add further type check to ensure not other control type with mataching id comes in selector.
$('input[type=checkbox][id^="checkbox_"]').each(function() {
});

Related

How to filter (show/hide) with two or more values in data attribute

I have a the following html:
<input id="check_1" type="checkbox" name="check" value="option_1">
<label for="check_1">Option 1</label>
<input id="check_2" type="checkbox" name="check" value="option_2">
<label for="check_2">Option 2</label>
<input id="check_3" type="checkbox" name="check" value="option_3">
<label for="check_3">Option 3</label>
<input id="check_4" type="checkbox" name="check" value="option_4">
<label for="check_4">Option 4</label>
<div class="productsBox" data-tag="option_1 option_2 option_3">Product 1</div>
<div class="productsBox" data-tag="option_1 option_4">Product 2</div>
And the following javascript:
<script>
window.onload=function(){
$('input').on('change', function () {
var $checked = $('input:checked');
if ($checked.length) {
$('.productsBox').hide();
$checked.each(function () {
var val = $(this).val();
$('.productsBox').filter('[data-tag*="'+val+'"]').show();
});
} else {
$('.productsBox').show();
}
});
}
</script>
So, if option 1 and option 4 are checked, the divs with product 1 and product 2 are shown, because they both contain the values option_1 OR option_4.
However, I would like to see that if option 1 and option 4 are checked only product 2 is shown because it contains the values option_1 AND option_4.
Is that possible? Any help is appreciated.
The issue is (1) in how you're deciding which .productsBox elements to show and (2) that you're applying the .filter().show() inside your .each() function.
Instead, you should create the complete filter condition by looping through the checked items, then apply the filter+show. In addition, at least based on your example data, you should use the "Attribute Contains Word Selector" (documentation) which is ~= instead of the contains selector *=. The former will ensure that option_10 is seen as distinct from option_1 in your data-tag filter.
Complete working JS:
$(function() {
$("input").on("change", function() {
var $checked = $("input:checked");
var $checkedFilter = '';
if ($checked.length) {
$(".productsBox").hide();
$checked.each(function() {
$checkedFilter = $checkedFilter + '[data-tag~="' + $(this).val() + '"]';
});
$(".productsBox").filter($checkedFilter).show();
} else {
$(".productsBox").show();
}
});
});
You can see I create a new string variable upfront called checkedFilter; this is where we'll build the dynamic filter for which .productsBox items to show. Then as we iterate through the checked checkboxes, we build the complete filter based on those items. In the example of Option 1 and Option 4 being checked, the value of checkedFilter is: [data-tag~="option_1"][data-tag~="option_4"].
Then outside the each loop of checked items, we invoke the .filter(checkedFilter).show() using the checkedFilter variable.
Working CodePen here: https://codepen.io/anon/pen/xzZEmd
If you select Options 1 & 4, only Product 2 appears; if you then select as a 3rd option Option 3, no product elements are displayed because none have 1, 3 & 4. If you select 1, 2 & 3, only Product 1 appears, etc.

Get Option Value OnClick with No Class/ID

I'm building an ecommerce website with 100 items. Each item has an item option (i.e. Small, Medium, Large). Each option has a value with an integer that identifies the option.
When the user clicks "Add to Cart," I need express that value as a variable. The problem is all of these items have the same exact class/id so I can't write an onclick function for each one.
How can I use jQuery to get the selected option value onclick without a class/id to identify it?
Basic structure of the item form:
<form>
<label>First Item</label>
<select>
<option value="6432">Large</option>
<option value="5332">Small</option>
</select>
<input type="submit" value = "Add to Cart">
</form>
Here's a Fiddle that shows what I'm talking about: http://jsfiddle.net/cusygh4o/
Thanks :-)
Try this:
$('input[type="submit"]').on('click', function(e) {
e.preventDefault();
alert($(this).prev('select').val());
});
Updated JSFiddle: http://jsfiddle.net/cusygh4o/1/
Note: if there is anything you can do to narrow down that 'input[type="submit"]' selector, you should. For example, if you have a parent element with an id, you could do something like '#shopping-items input[type="submit"]'.
jsFiddle Demo
Just base it off where the click occurred.
$("input[type=submit]").click(function(){
alert($(this).parents("form").find("select").val());
});
Use this
jQuery(document).ready(function(){
var selectedValue;
$('input[type="submit"]').on('click', function() {
selectedValue=jQuery('form select').val();
alert(selectedValue);
})
})
Lots of different ways to go about it: http://jsfiddle.net/cusygh4o/2/
$('form').on('submit', function(e) {
alert($(this).find('select').val());
});
Try this
<script>
function getValue(e){
value = e.closest('form').find('select').find(":selected").text();
alert(value);
}
</script>
Then replace all your <input type="submit" value = "Add to Cart"> with <input onclick="getValue($(this))" type="submit" value = "Add to Cart">

JQuery - check checkboxes based on select list value

Im very, very new to jquery. Im trying to do something that most likely seems elementary to most of the gurus here, but I think I have been messing with it for so long, that I must be overlooking something very simple.
I have a large list of checkboxes (85 in total) that need to be checked based on the value selected in a select list. Both the select list and the checkboxes are created dynamically via an ASP page/database query.
Link to fiddle: http://jsfiddle.net/v9p5C/21/
HTML:
<select id="roleID">
<option data-filter=''>ID</option>
<option data-filter='200'>200</option>
<option data-filter='300'>300</option>
<option data-filter='400'>400</option>
</select>
<BR>
<BR>
<input type="checkbox" data-tags='["200"]'>Create
<br>
<input type="checkbox" data-tags='["200,300"]'>Edit
<br>
<input type="checkbox" data-tags='["200","300, 400"]'>View
<br>
<input type="checkbox" data-tags='["200"]'>Delete
<br>
<input type="checkbox" data-tags='["200"]'>Archive
<br>
SCRIPT:
$(function () {
$(document).on('change', function (e) {
var filter = $(this).data('filter');
$('input[type="checkbox"]').each(function () {
var $checkbox = $(this);
var tags = $checkbox.data('tags');
$.each(tags, function () {
if (filter == this) $checkbox.prop("checked", !$checkbox.prop("checked"));
});
});
});
});
Your jQuery will need to look more like this:
$(function () {
$('#roleID').on('change', function (e) {
var filter = $(this).val();
$('input[type="checkbox"]').removeAttr('checked');
$('input[type="checkbox"][data-tags*="'+filter+'"]').attr('checked','checked');
});
});
This is a very simple way of creating that functionality. You can view the fiddle here:
http://jsfiddle.net/m0nk3y/kjnoovL0/1/
the var filter = $(this).data('filter'); line was attempting to get the data-filter value from the select element, not the selected option element. Here's how you would grab the selection option's data-filter:
var filter = $('option:selected', this).data('filter');
updated fiddle:
http://jsfiddle.net/v9p5C/52/
(there were a couple of other minor bugs in the fiddle that are also fixed)

is there a defaultValue property for radio select?

I am wondering if there is a way to reset a radio to it's originally selected option. I know of defaultValue for inputs but is there a way to make it so that I can reset the radios back to their originally selected value on page load?
I am not wanting to simply unselect all radios. I am trying to put them back to their originally selected value.
Thanks for any info.
Yes, radio inputs do have defaultValue property, but what you are looking for is the defaultChecked property:
$('input[type=radio]').prop('checked', function() {
return this.defaultChecked;
});
That being said, if you want to reset the form you can use the reset method of the HTMLFormElement object:
$('#formElement').get(0).reset();
I think you want this
<form action="">
<input type="radio" name="gender" value="male" checked="true"/>Male
<input type="radio" name="gender" value="female"/>Female
<input type="reset" value="reset"/>
</form>
Any time you will reset the form, the male radio button will be selected.
I will rather make a jQuery plugin like this:
$.fn.defaultVal = function (checked) {
if(checked === true || checked === false) {
$(this).attr("data-default", checked);
return;
}
if(!$(this).attr("data-default")) {
console.log("No default value assigned!");
return;
}
return $(this).attr("data-default");
}
JSFIDDLE LINK UPDATE
Working Demo is here: JSFIDDLE

How to check a Particular Radio Box in a "Group" using JavaScript

I have a radio box group and I need to select a given radio box using javascript as in the following case, I have to check option with value D3
<input type="radio" name="day" id="day" value="D1" />D1
<input type="radio" name="day" id="day" value="D2" />D2
<input type="radio" name="day" id="day" value="D3" />D3
<input type="radio" name="day" id="day" value="D4" />D4
How can the third option for example be checked?
Be sure putting this radio group in a form and change the theNameOfTheForm to your form's name.
<form name="theNameOfTheForm">
..
..
..
</form>
The java-script function:
<script type="text/javascript">
function select_radio_value(theValue)
{
for (var i=0; i < document.theNameOfTheForm.day.length; i++)
{
if (document.theNameOfTheForm.day[i].value == theValue)
{
document.theNameOfTheForm.day[i].checked = true;
}
}
}
</script>
Now you can use it as a js function on any event. for instance:
<input type='button' name='c3' value='Click Here to check the D3 radio' onClick="javascript:select_radio_value('D3')">
Normally, you'd use document.getElementById('day').val or jQuery('#day').val(). That is, if they have different ids. If they share the id, I'm not sure you can with document.getElementById since it assumes that the ids are different, but perhaps
jQuery('#day')[3].val()
could work, because jQuery actually returns an array of elements that match the criteia
Remove the unique ID from each of the checkboxes. You should only have ONE unique ID on a page.
In JavaScript, access the third checkbox in this group with the following and set it to checked:
var inputs = document.getElementsByTagName('input');
inputs[2].setAttribute('checked', 'checked');
OR, you can simply add checked=checked to your HTML.
function selectRadio(toBeSelectedRadioIndex)
{
var radioElements = document.getElementById('day');
radioElements[toBeSelectedRadioIndex].checked = true;
}
In many cases you need to have Id names different for your elements.
You can then give them same name and use getElementsByTagName instead.
The the code will look like...
function selectRadio(toBeSelectedRadioIndex)
{
var radioElements = document.getElementsByTagName('day');
radioElements[toBeSelectedRadioIndex].checked = true;
}
I would give the radio buttons different ids and then do the following :
d3.select("input#thirdRadio").property("checked", "true");

Categories

Resources