How to select all elements in name array? - javascript

I am trying to sum a collection of radio selections using jQuery.
<input name="cost[alpha]" type="radio" >
<input name="cost[beta]" type="radio">
<input name="cost[delta]" type="radio">
...
$('input[name="cost[*]"]').each( function() {
...
}
This does not function as it tries to resolve an input with the name "cost[*]". Ideally I would like to iterate over any element in the cost array. Is there a preferred way of doing this with jQuery? I have other elements in my form that use the radio type so selecting radios in general is not a valid option.

Make the attribute selector the "starts with" selector (^=):
$('input[name^="cost"]').each(function() {
...
});
If you find that you have other input elements that start with "cost" or even "cost[", then perhaps you want to think about changing the way you're querying for the elements. One alternative would be adding a special class name to the elements you're targeting and forget about their names altogether. For example:
<input name="cost[alpha]" type="radio" class="form-cost">
<input name="cost[beta]" type="radio" class="form-cost">
<input name="cost[delta]" type="radio" class="form-cost">
And then your selector is very simple and very targeted:
$('input.form-cost').each(function() {
...
});
You might get the best performance out of simply wrapping the elements in a container with a unique id or class name, and querying for input elements that it contains (as suggested by Allende in the comments):
<div id="cost-inputs">
<input name="cost[alpha]" type="radio">
<input name="cost[beta]" type="radio">
<input name="cost[delta]" type="radio">
</div>
$('#cost-inputs input').each(function() {
...
});

Try with contains selector in jquery
$("input[name*='cost[']").each(function(){});

Try:
var sum = 0;
$("input[name^='cost']").each(function() {
sum += Number($(this).val());
});
About "Starts With Selector": [name^="value"]
https://api.jquery.com/attribute-starts-with-selector/

Related

how can i get value of multiple checked box and perform increment using value from checked box

i can's seem to get the element by using id with query selector. Is there a way to check if the checkbox were checked using document.getelementbyId?
<script>
function checked(a,b,c){
var marked = (a+b+c)
document.write(marked);
}
function filled(){
var value1 = document.querySelector("#1:checked").value;
var value2 = document.querySelector("#2:checked").value;
var value3 = document.querySelector("#3:checked").value;
checked(value1,value2,value3);
}
<body>
<input class="chk1" id="1" type="checkbox" value="10"/>
<input class="chk2" id="2" type="checkbox" value="20"/>
<input class="chk3" id="3" type="checkbox" value="30"/>
<button name="submit" onclick="filled()" type="button" style="width: 100px; height: 100px;" >Submit</button>
</body>
Your IDs aren't valid. Even if they were (such as if you changed them to start with a letter), if a checkbox isn't checked, the querySelector will return null (so accessing the .value won't work).
Remove the IDs and use querySelectorAll instead. To make things concise, I'd give them all a single class and then the :checked pseudo-selector combined with the class will select all checked boxes.
You should also really avoid inline handlers if at all possible, they have they have way too many problems to be worth using nowadays.
document.querySelector('button').addEventListener('click', () => {
const checkedBoxes = document.querySelectorAll('.chk:checked');
const sum = [...checkedBoxes].reduce((a, b) => a + Number(b.value), 0);
console.log(sum);
});
button {
width: 100px;
height: 100px;
}
<input class="chk" type="checkbox" value="10">
<input class="chk" type="checkbox" value="20">
<input class="chk" type="checkbox" value="30">
<button>Submit</button>
using numbers, punctuation or special characters in the value of an ID may cause trouble in other contexts (e.g., CSS, JavaScript, regex).
For example, the following ID is valid in HTML5:
<div id="1"> ... </div>
However, it is invalid in CSS because selectors cannot be a digit or start with a digit but can be inbetween or end with a digit.
So just change the values of your ID attributes in your html and where u referenced them in your javascript.
Be sure to not miss any semi colons

How can I disable all checkboxes on webpage at once?

I have several sets of checkboxes on a webpage. I want to uncheck them all with javascript. Right now, I do it by looking for the names of each set and unchecking them with FOR loops like this...
for (i=0;i<document.getElementsByName("myboxes").length;i++) {
document.getElementsByName("myboxes")[i].checked=false;}
for (i=0;i<document.getElementsByName("moreboxes").length;i++) {
document.getElementsByName("moreboxes")[i].checked=false;}
for (i=0;i<document.getElementsByName("evenmoreboxes").length;i++) {
document.getElementsByName("evenmoreboxes")[i].checked=false;}
I'm looking for a way to target them all with one loop. I could do getElementsByTagName('input') to target all INPUTS, but that's a problem because I have some radio inputs that I don't want to uncheck. Is there a way to target all checkbox inputs?
Thanks for the suggestions. I just thought of something. Each NAME I use has the word "boxes" in it, myboxes, moreboxes, evenmoreboxes. Is there a way to target the word "boxes" in in the name, like a wildcard, something like document.getElementsByName("*boxes") that way if I add a set of checkboxes at some point that I don't want to uncheck I can simply name them differently.
You can select all checked checkboxes and reset their state:
function uncheckAll() {
document.querySelectorAll('input[name$="boxes"]:checked')
.forEach(checkbox => checkbox.checked = false);
}
<input type="checkbox"/>
<input type="checkbox" name="a_boxes" checked/>
<input type="checkbox"/>
<input type="checkbox" name="b_boxes" checked/>
<input type="checkbox" name="c_boxes" checked/>
<button onclick="uncheckAll()">Reset</button>
you can use document.querySelectorAll('input[type="checkbox"]'); to get a list of them all. then run your loop
My proposal is:
document.querySelectorAll("[name=myboxes], [name=moreboxes], [name=evenmoreboxes]").forEach((e) => echecked=false);
document.querySelectorAll("[name=myboxes], [name=moreboxes], [name=evenmoreboxes]").forEach((e) => e.checked=false);
<input type="checkbox" name="myboxes" value="1" checked>1<br>
<input type="checkbox" name="moreboxes" value="2" checked>2<br>
<input type="checkbox" name="evenmoreboxes" value="3" checked>3<br>
As suggested by #imjared, you can use querySelectorAll, but you will have to iterate over it:
querySelectorAll('input[type="checkbox"]').forEach(c => c.checked = false);
Here is the doc for querySelectorAll

Is it possible to use checkbox change with the combination of class?

This is my code with checkboxes with one and two classes as shown below
<input type="checkbox" class="one" value="1">
<br/>
<input type="checkbox" class="two" value="2">
<br/>
<input type="checkbox" class="one" value="3">
<br/>
If the checkbox is checked or unchecked , i have the below code which gets called
$(document).on('change', '.[type="checkbox"]', function(event, data){
alert('checked ');
});
My question is , how can i use class also in the event handler ??
I have tried this way
$(document).on('change', '.one .[type="checkbox"]', function(event, data){
alert('checked ');
});
$(document).on('change', '.two .[type="checkbox"]', function(event, data){
alert('checked ');
});
http://jsfiddle.net/FdEhf/32/
This is a wrong selector:
'.[type="checkbox"]'
You can't have a dot . before attribute selectors.
Now to answer your question you can use this way:
'.one[type="checkbox"]'
// make sure you don't have any space in between.
Well you can have a common class name to each checkbox and you can bind a change event on that class:
$('.commonClass[type="checkbox"]').on('change', function(event, data) {
if (this.checked) {
console.log(this.classList[1]+' checked ');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="commonClass one" value="1">
<br/>
<input type="checkbox" class="commonClass two" value="2">
<br/>
<input type="checkbox" class="commonClass three" value="3">
<br/>
You don't need to have a event delegation way to bind any event unless you have dynamically generated :checkbox elements.
Yes it is possible.
You can use this selector:
.one[type="checkbox"]
To break it down, this selector will match any element with the .one class that as a type attribute equal to checkbox.
You could also just have [type="checkbox"] as the selector and then inside the change handler inspect the elements class. This would be useful if you wanted to have slightly different functionality between different checkboxes -
$(document).on('change', '[type="checkbox"]', function(event, data){
var classes = $(this).attr('class').split(' '); // may be multiple classes - split them into an array
if ( $.inArray( 'one', classes ) ){
alert('.one was changed!');
} else {
alert('some other checkbox was changed!');
}
});
For this simple example it might be overkill but it would allow you to further customise different checkboxes.
First of all remove one extra "." before that [type="checkbox"] and second use only classes like .one .two as event listeners and you'll get the result as per your need.

Same id with diffent classname in html and javascript

I have a situation where
<label id="studentName" class="firstClass> </label>
<label id="studentName" class="secondClass> </label>
<label id="registerNumber" class="firstClass> </label>
<label id="registerNumber" class="secondClass> </label>
Now, I have to identify each tag uniquely and replace the innerHTML with some value, using class and id.
How Can I achieve this from javascript/ios side ?
You want to switch the Id and classes around. You CANT have 2 of the same ID's But you can have multible Classes with the same name.
<label id="firststudentName" class="studentName> </label>
<label id="secondstudentName" class="studentName> </label>
<label id="firstregisterNumber" class="registerNumber> </label>
<label id="secondregisterNumber" class="registerNumber> </label>
You can use
elements = document.getElementsByClassName(names);
and loop on the results, there is also hasClass function.
But normally an ID should be unique.
try this with jquery:
function checkUnique(className){
var count = 0;
var ids = '';
$('.' + className).each(function(i){
if(ids.indexOf($(this).attr('id')) != -1){
$(this).attr('id',$(this).attr('id') + i);
}
ids += $(this).attr('id');
})
}
This is invalid HTML, see here: http://www.w3schools.com/tags/att_global_id.asp
If you're iterating through e.g. a number of students, make sure to use the cycle for the id so you have
id="studentName1"
id="studentName2"

How to get a radio button index number from a each function in jquery

When using the each() function in jquery for a group of, let's say, 3 radio buttons, how do I retrieve the 3rd button so when it's checked something happens?
Basically how do I choose the element I want to work with from the each() function?
Here is my coding:
HTML:
<form id="orderDefinition" name="orderDefinition">
<fieldset>
<input type="radio" name="radioGroup" /><label for="">radio 1</label>
<input type="radio" name="radioGroup" /><label for="">radio 2</label>
<input type="radio" name="radioGroup" /><label for="">radio 3</label>
</fieldset>
</form>
jQuery:
var radioBtnCollection = $("#orderDefinition input:radio");
$(radioBtnCollection).each(function(){
// From here, I don't know how to get the element
});
Thanks in advance.
You can refer to the element using the this operator:
radioBtnCollection.each(function(){
alert(this.name);
});
Or by using the arguments supplied to the function:
radioBtnCollection.each(function(index, element){
if (index == 2 && element.checked)
alert("3rd element is checked!");
});
If you want to perform any jQuery methods on the element, you will need to wrap it with jQuery. For the first example, $(this), for the second example $(element).
You can just get the third radio button using :eq(2), instead of each:
if ($("#orderDefinition input:radio:eq(2)")[0].checked)
alert("3rd element is checked!");
Use this wrapped as a jQuery object:
$(radioBtnCollection).each(function(){
// this points to the element being iterated
$(this)
});

Categories