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.
Related
Radio buttons, the first one is checked by default:
<div class="shipping">
<div class="title">Select shipping method</div>
<label><input type="radio" name="shipping" value="courier-dpd" checked="checked">Courier DPD</label>
<label><input type="radio" name="shipping" value="personal">Personal pick up</label>
<button>Next</button>
</div>
Js:
$(document).on('click', '.shipping button', function() {
let val = $('.shipping').find('input[name="shipping"]:checked').val()
console.log(val);
}
Even if I manually switch the radio buttons and select the second one, jQuery keeps getting the value of the first radio button, independently on user selection.
Why is that? I can't find solution.
Edit 2: Added JS code from updated question. It seems to work here.
Edit: Added submit button to demonstrate submit action.
Well, are you calling console.log after changing the value? I created a snippet below and it works fine.
$(function() {
let val = $('.shipping').find('input[name="shipping"]:checked').val()
console.log(val);
/*$('#btn').on('click', function() {
let val = $('.shipping').find('input[name="shipping"]:checked').val()
console.log(val);
})*/
$(document).on('click', '.shipping button', function() {
let val = $('.shipping').find('input[name="shipping"]:checked').val()
console.log(val);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="shipping">
<div class="title">Select shipping method</div>
<label><input type="radio" name="shipping" value="courier-dpd" checked="checked">Courier DPD</label>
<label><input type="radio" name="shipping" value="personal">Personal pick up</label>
<button>Next</button>
</div>
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
How will I get the value of the radio button after clicked on the button?
document.getElementById('btnKnop1').addEventListener('click', function(){
var kleuren = document.querySelectorAll('input[type=radio');
for (var i in kleuren) {
kleuren[i].onclick = function(){
document.getElementById('divResult'). innerHTML =
'Gekozen kleur: ' + this.value;
}
}
});
<input type="radio" name="radioGroup" value="rood" checked />Rood</br />
<input type="radio" name="radioGroup" value="blauw" />Blauw</br />
<input type="radio" name="radioGroup" value="geel" />Geel</br />
<input type="radio" name="radioGroup" value="groen" />Groen</br />
<button id="btnKnop1">Check de waarde!</button>
<div id="divResult"></div>
Now it depends on click on the radio button, but I'd to depend on click on the button
The issue seems to be be the inner click event on the radio button. If you change the loop to an if statement checking if it's checked then you can output the value on the button click:
document.getElementById('btnKnop1').addEventListener('click', function(){
var kleuren = document.querySelectorAll('input[type=radio');
for (var i in kleuren) {
if (kleuren[i].checked === true) {
document.getElementById('divResult'). innerHTML =
'Gekozen kleur: ' + kleuren[i].value;
}
}
});
<input type="radio" name="radioGroup" value="rood" checked />Rood</br>
<input type="radio" name="radioGroup" value="blauw" />Blauw</br>
<input type="radio" name="radioGroup" value="geel" />Geel</br>
<input type="radio" name="radioGroup" value="groen" />Groen</br>
<button id="btnKnop1">Check de waarde!</button>
<div id="divResult"></div>
First of all, please consider using english-named variables, it will improve readability by a lot.
Second of all, line
var kleuren = document.querySelectorAll('input[type=radio');
has a typo, it's missing a closing square bracket - ].
To check a checkbox/radio button value you can use checkbox.checked, where checkbox is your DOM object selected by querySelector.
You're basically already doing it. When you click the button, in the click handler for the button, just grab the radio button element using a selector (either class or id), with a "querySelector" call (just like you're doing). Inspect that element for whatever property makes sense (probably "checked").
Something like:
<button onclick="onClick ()">Click Me</button>
...
onClick () {
const kleuren = document.querySelector ( [mySelectorByIDorClass, etc.] );
console.log ( kleuren.checked );
}
See here:
https://www.w3schools.com/jsref/prop_radio_checked.asp
The checked property will tell you whether the element is selected:
if (document.getElementById('id').checked) {
var variable = document.getElementById('id').value;
}
I have two checkboxes on a page and I want them to act as only one. For example, I select one, and the other is selected automatically, and vice-versa.
I've managed to select both of them at once, but I can't seem to figure out a way to deselect them at once.
And what's bothering me the most, is that it's probably a super simple line of code that I'm simply not remembering.
Is there a way to do this?
Is this what you're looking for?
$(".test").change(function () {
$(".test").attr("checked", this.checked);
});
<input type='checkbox' class='test'>A<br />
<input type='checkbox' class='test'>B<br />
Here is a solution in pure javascript:
// Select all checkboxes using `.checkbox` class
var checkboxes = document.querySelectorAll('.checkbox');
// Loop through the checkboxes list
checkboxes.forEach(function (checkbox) {
// Then, add `change` event on each checkbox
checkbox.addEventListener('change', function(event) {
// When the change event fire,
// Loop through the checkboxes list and update the value
checkboxes.forEach(function (checkbox) {
checkbox.checked = event.target.checked;
});
});
});
<label><input type="checkbox" class="checkbox"> Item 1</label>
<br>
<label><input type="checkbox" class="checkbox"> Item 2</label>
$(document).ready(function() {
$('#check_one').change(function() {
$('#check_two').prop('checked', $('#check_one').prop('checked'));
});
$('#check_two').change(function() {
$('#check_one').prop('checked', $('#check_two').prop('checked'));
});
});
<form>
<label>Simple checkbox</label>
<input type="checkbox" id="check_one" />
<label>Complicated checkbox</label>
<input type="checkbox" id="check_two" />
</form>
Assuming you have two checkboxes named differently but working in concert, this code would work
html:
<input type="checkbox" id="1" class="handleAsOne">
<input type="checkbox" id="2" class="handleAsOne">
javascript (jquery):
$('.handleAsOne').on('change'){
$('.handleAsOne').prop('checked', false);
$(this).prop('checked', true);
}
if i understood your question correctly you are looking for something like this.
I want to hide a div (AppliedCourse), when radi button value is Agent. I wrote below code but it is not working.
Any idea?
$('#HearAboutUs').click(function() {
$("#AppliedCourse").toggle($('input[name=HearAboutUs]:checked').val()='Agent');
});
<tr><td class="text"><input type="radio" name="HearAboutUs" value="Press">Press & Print media
<input type="radio" name="HearAboutUs" value="Internet">Internet
<input type="radio" name="HearAboutUs" value="Agent">Agent
<input type="radio" name="HearAboutUs" value="Friend">Friend
<input type="radio" name="HearAboutUs" value="Other" checked="checked">Other</td></tr>
Either your HTML is incomplete or your first selector is wrong. It is possible that your click handler is not being called because you have no element with id 'HeadAboutUs'. You might want to listen to clicks on the inputs themselves in that case.
Also, your logic is not quite right. Toggle hides the element if the parameter is false, so you want to negate it using !=. Try:
$('input[name=HearAboutUs]').click(function() {
var inputValue = $('input[name=HearAboutUs]:checked').val()
$("#AppliedCourse").toggle( inputValue!='Agent');
});
I have made a JSFiddle with a working solution: http://jsfiddle.net/c045fn2m/2/
Your code is looking for an element with id HearAboutUs, but you don't have this on your page.
You do have a bunch of inputs with name="HearAboutUs". If you look for those, you'll be able to execute your code.
$("input[name='HearAboutUs']").click(function() {
var clicked = $(this).val(); //save value of the input that was clicked on
if(clicked == 'Agent'){ //check if that val is "Agent"
$('#AppliedCourse').hide();
}else{
$('#AppliedCourse').show();
}
});
JS Fiddle Demo
Another option as suggested by #Regent is to replace the if/else statement with $('#AppliedCourse').toggle(clicked !== 'Agent');. This works too.
Here is the Fiddle: http://jsfiddle.net/L9bfddos/
<tr>
<td class="text">
<input type="radio" name="HearAboutUs" value="Press">Press & Print media
<input type="radio" name="HearAboutUs" value="Internet">Internet
<input type="radio" name="HearAboutUs" value="Agent">Agent
<input type="radio" name="HearAboutUs" value="Friend">Friend
<input type="radio" name="HearAboutUs" value="Other" checked="checked">Other
</td>
Test
$("input[name='HearAboutUs']").click(function() {
var value = $('input[name=HearAboutUs]:checked').val();
if(value === 'Agent'){
$('#AppliedCourse').hide();
}
else{
$('#AppliedCourse').show();
}
});