jQuery radio button select only one (ID) - javascript

I have 2 groups raido buttons, they have different unique IDs, how to make they can be selected only one for each group. Thanks
<group>
<input type="radio" id="u1"/>1
<input type="radio" id="u2"/>2
<input type="radio" id="u3"/>3
</div >
</group>
<group>
<input type="radio" id="T1"/>4
<input type="radio" id="T2"/>5
<input type="radio" id="T3"/>6
</group>
http://jsfiddle.net/pZdWu/
I don't want to change the html, just want to use jQuery to achieve

If you really must use the existing HTML, then I'd suggest amending the HTML via jQuery to simply use the default functions of a radio input:
​$('group').each(
function(i,e){
$(e).find('input:radio').attr('name', 'group' + i);
});​​​​​
JS fiddle demo.
References:
attr().
each().

Give each item in the group a common name using the name attribute.....
<input type="radio" name="group1" id="u1"/>1
<input type="radio" name="group1" id="u2"/>2
<input type="radio" name="group1" id="u3"/>3

Using jQuery, you can use something like this:
http://jsfiddle.net/pZdWu/5/
$(document).ready(function () {
$("input[type=radio]").click(function () {
var $this = $(this);
$this.siblings("input[type=radio]").prop("checked", false);
});
});
But this assumes your HTML structure is exactly as you provided.
If the radio buttons have any kind of wrapping HTML on them, or are grouped inside any way, the use of siblings won't work. You might have to use something like:
http://jsfiddle.net/pZdWu/7/
$(document).ready(function () {
$("input[type=radio]").click(function () {
var $this = $(this);
$this.parents("group:first").find("input[type=radio]").not($this).prop("checked", false);
});
});
And obviously change the use of "group" to whatever you are actually using (I thought I saw you edited your original question to not use <group>).

Related

Why my "change" event hasn't worked as intended?

Okay, so I'm practicing my JS and HTML, my current code looks like this:
document.querySelector('input[name="answer"]:checked').checked = false;
let Select = document.querySelector('input[name="answer"]');
Select.addEventListener('change', function(event) {
alert(event.target.value)
})
<div>
<label><input type="radio" name="answer" value="1" checked="checked">1</label>
<label><input type="radio" name="answer" value="2">2</label>
</div>
My aim is to cancel first radio's "checked", then add an event that will show each of radio's value whenever I choose/"checked" it, but as you may notice, so far the alert will only shows up if I choose the first radio. So if I may ask, where did I do wrong and how can I fix it?
p.s. For the sake of practicing, the HTML has to stay the same. No adding Id or other selector.
You only get the first with querySelector
The querySelector(...:checked) will work because you can only have one checked radio
I really like to delegate - it is recommended and makes a lot of sense
document.querySelector('input[name="answer"]:checked').checked = false;
let radDiv = document.getElementById('radioDiv');
radDiv.addEventListener('change', function(event) {
const tgt = event.target;
if (tgt.matches("[type=radio][name=answer]")) { // check we have the right elements
alert(tgt.value)
}
})
<div id="radioDiv">
<label><input type="radio" name="answer" value="1" checked="checked">1</label>
<label><input type="radio" name="answer" value="2">2</label>
</div>
document.querySelector('input[name="answer"]:checked').checked = false;
let Select = document.querySelectorAll('input[name="answer"]');
Select.forEach(el => el.addEventListener('change',function (event) {
Select.forEach(e => alert(e.value));
}))
<div>
<label><input type="radio" name="answer" value="1" checked="checked">1</label>
<label><input type="radio" name="answer" value="2">2</label>
</div>
let Select = document.querySelectorAll('input[name="answer"]');
Select.forEach(function(elem) {
elem.addEventListener("change", function(event) {
alert(event.target.value)
});
});
Use above for element selector instead of querySelector which returns a single object (first match)
querySelectorAll returns an array of elements.

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

Get value checkbox javascript

i have an array of checkbox (to use with php), bu i want to use ajax to make somethings with this values from checkbox, i want to get the value from each checkbox and make an ajax request.
I have this:
$("#checked").each(function(i, val){
var k = $(i).value();
console.log(k);
});
but no success.
html:
<input id="checado" type="checkbox" name="ids[]" value="78">
<input id="checado" type="checkbox" name="ids[]" value="79">
<input id="checado" type="checkbox" name="ids[]" value="80">
<input id="checado" type="checkbox" name="ids[]" value="81">
With a small change to your HTML you can use the following JavaScript (demo):
<input class="checado" type="checkbox" name="ids[]" value="78"> 78<br/>
<input class="checado" type="checkbox" name="ids[]" value="79"> 79<br/>
<input class="checado" type="checkbox" name="ids[]" value="80"> 80<br/>
<input class="checado" type="checkbox" name="ids[]" value="81"> 81<br/>
<button id='Submit'>Submit</button>
<script>
$('#Submit').on('click', function() {
var values = []
$('.checado:checked').each(function () {
var e = $(this);
values.push(e.val());
});
alert(values);
});
</script>
For a more detailed breakdown of what is going on, the check boxes have a checked state and a value. the jQuery Selector $('.checado:checked') will return just the checked check boxes (You should use class when you have multiple elements and id only when you are identifying a single element, browsers and CSS can appear lazy about this but incorrect usage will yield unpredictable results). The other change is to grab the values by the jQuery method .val() which helps hide the input type and browser specific ways values are fetched.
You're using jQuery, which uses it's own .val() method. Replace .value() with .val().

Getting the selected radio without using "Id" but "name"

I was trying to get selected radio button by using "document.getElementByName('nameOfradio')" because all of the radio buttons share the same name. But, nothing happened. I tried the same thing with document.getElementById('nameOfradio') and worked well.However, I had to give unique id for all of the radio buttons. So that, it turns ugly when i have 20 radio buttons. As a result, what I wanted is making a shortcut. How can i get the value of selected radio button by using their "name"? Codes;
Html
<input type="radio" name="nameOfradio" value="onm1" /> 1
<input type="radio" name="nameOfradio" value="onm2" /> 2
<input type='button' onclick='radio3()' value='Submit' />
</form>
Ajax(relavant part of radio3())
var radioPushed = document.getElementByName('nameOfradio').value;
var queryString = "?radioPushed=" + radioPushed;//to send the value to another file
ajaxRequest.open("GET", "radio_display.php" + queryString, true);
ajaxRequest.send(null);
As i said document.getElementById worked but it requires too much work:( How can i make it simplier by using common feature of radio buttons, instead of giving them unique id? A short explanation why i could not make it would be very helpful(new in javascript and ajax)
This line:
document.getElementByName('nameOfradio').value
should be:
document.querySelector('input[name=nameOfradio]:checked').value;
using querySelector
Note that CSS pseudo-classes are accessed by a colon (:).
document.querySelector('input[name=nameOfRadio]:checked').value
Eg:-
<form>
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</form>
document.querySelector('input[name=gender]:checked').value
Also, you can add a checked attribute to a default radio button among the group of radio buttons if needed
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
Save yourself some pain in the later js dev and use a js library like jQuery. Then you can do something like $('input[name=radioName]:checked').val()
This is exactly why you should use a javascript library.
document.querySelector('input[name=nameOfradio]');
for example is not supported before IE8.
Let the library handle the browser craziness.
In jQuery you can just use $('input[name=radioName]:checked').val() or $("form").serialize() and be done with it.
You can use the class property if your looking for a quick solution. Many elements can have the same class. use the command:
document.getElementsByClass('nameOfradio');
In addition you should use the correct form of getting elements by name which is:
document.getElementsByName('nameOfradio');
You can also use the following code to find the selected radio value as follows:
radioObj=document.getElementsById('nameOfradio');
var radioLength = radioObj.length;
if(radioLength == undefined) {
if(radioObj.checked) {
return radioObj.value;
} else {
return "";
}
}
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";

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