Unable to get the value of radio buttons - javascript

I am not able to get second and third radio buttons values.
my code just gives me the first radio button value when I select this.
this is my radio buttons and the function by which I want to store the value of the radio button.
<input type="radio" id="choiced" name="Q0_choice" value="one">
<input type="radio" id="choiced" name="Q0_choice" value="2">
<input type="radio" id="choiced" name="Q0_choice" value="iii">
next.onclick = function () {
if (document.getElementById('choiced').checked) {
ans = document.getElementById('choiced').value;
}
}

This is because ID values must be unique - so it's grabbing the first element on the page it finds with the ID of choiced. You'll want to give each a unique ID, and you can use the name attribute for grouping radio button. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio

Try
document.querySelector('#choiced:checked')
This query return checked radio button.

You should not have the same ID for those inputs:
<input type="radio" id="choiced" name="Q0_choice" value="one">
<input type="radio" id="choiced2" name="Q0_choice" value="2">
<input type="radio" id="choiced3" name="Q0_choice" value="iii">
Then to get the selected you have to get them by it's name property. You can loop to check which one is selected.
next.onclick = function () {
const radios = document.getElementsByName('Q0_choice');
radios.forEach((radio) => {
if (radio.checked){
console.log(radio.value);
}
})
}

Related

Unchecked input checkbox with identical ids

I'm trying to get the values of an input of type checkbox with the same ID, and try to get the click (the checked), to the one with the value 1
but when I do the console.log I only get the value of the first input and it does not get both values.
i.e. to bring me the value number 2 of the first one and not 2 and 1.
<script>
var s = document.getElementById("switchA").value;
console.log(s);
</script>
These inputs are of checkbox type so if one of them has value two it should be unchecked.
<input type="checkbox" name="asd" id="switchA" value="2">
<input type="checkbox" name="asdf" id="switchA" value="1">
You shouldn't be giving the same id to multiple elements on a page. However, assuming you are not able to change the HTML, you can use the following to select multiple elements with the same id:
var s = document.querySelectorAll("[id='switchA']");
You should use a name or class instead to group the checkboxes. Ids are meant to be unique in a document.
const vals = [...document.querySelectorAll('input[type=checkbox][name=someName]')]
.map(x => x.value);
console.log(vals);
<input type="checkbox" name="someName" value="2">
<input type="checkbox" name="someName" value="1">
However, you could use an attribute selector to obtain all elements with a specific id, but that is not recommended.
const vals = [...document.querySelectorAll("[id=switchA]")]
.map(x => x.value);
console.log(vals);
<input type="checkbox" name="asd" id="switchA" value="2">
<input type="checkbox" name="asdf" id="switchA" value="1">

How to check whether a radio buttons and checkboxes are selected in form loop in jQuery?

I am making my first js plugin to validate the html form. I have figure it out for text fields but having some issues in choosing best way to validate radio buttons and checkbox. Since there can be multiple radio groups, each group having many radio buttons. What i am doing is looping around form elements like below.
_self.on("submit", function(event) {
console.log('form submitted ');
_self.find('.'+settings.errorClass).each(function(){
let type = $(this).attr('type');
let val = $(this).val();
validate(type, val);
});
validate = function(type, val) {
console.log(type);
switch (type) {
case 'text':
validateText(val);
break;
case 'radio':
validaRadio(val);
break;
case 'checkbox':
validaCheckbox(val);
break;
default:
}
Now in above code validaRadio function is called for every radio button in each group which i do not want. I want to validate radio button by group (name). So that if there are two radio groups each having four radio buttons then validateRadio function should be called twice by each radio group not eight times.
Let me know if you guys some better solutions to above problem.
Create an array of checkedRadioNames for names you've already sent to the verifier. If there's a radio button with a name already verified, skip it.
_self.on("submit", function(event) {
console.log('form submitted ');
const checkedRadioNames = [];
_self.find('.'+settings.errorClass).each(function(){
const type = $(this).attr('type');
const val = $(this).val();
if (type === 'radio') {
const name = $(this).attr('name');
if (checkedRadioNames.includes(name)) return;
validaRadio(val, name);
} else validate(type, val);
});
Your approach isn't necessary. All you have to do is get a collection for each set of radio buttons and check the length of the checked items and see if that length is 0.
var groups = Array.prototype.slice.call(document.querySelectorAll("fieldset"));
// Set up an event callback that checks validity
document.querySelector("button").addEventListener("click", function(){
console.clear();
// Loop over the button groups (each group is in a container element of some kind - a fieldset here)
groups.forEach(function(g){
// Look in the container element for the checked buttons in the group
// and see if the amount of checked buttons is zero
if(g.querySelectorAll("input[name^='group']:checked").length === 0){
// If so, none were selected in that group
console.log("You must select a choice in " + g.dataset.group);
}
});
});
<fieldset data-group="Group One">
<input type="radio" name="group1" value="One"> One
<input type="radio" name="group1" value="Two"> Two
<input type="radio" name="group1" value="Three"> Three
<input type="radio" name="group1" value="Four"> Four
</fieldset>
<fieldset data-group="Group Two">
<input type="radio" name="group2" value="One"> One
<input type="radio" name="group2" value="Two"> Two
<input type="radio" name="group2" value="Three"> Three
<input type="radio" name="group2" value="Four"> Four
</fieldset>
<button type="button">Check</button>

working with radio buttons passing the status along with value?

I am writing code for radio buttons where there are 3 radio buttons like YES, NO and ALL. I am using same class name for all the 3 and also binding a value for them. If user clicks on one of the three Am able to pass the corresponding value on onclick event but my problem is how to know whether user clicks on which radion button among the three buttons like if user clicks on 'All' radio button I want to perform some type of action else if user clicks on 'Yes' option then some different action, etc. how to know user clicks on which radio button? mycode is below:
<input type="radio" name="select_option" class="select_option" value="<?=$row_id;?>">All
<input type="radio" name="select_option" class="select_option" value="<?=$row_id;?>">Yes
<input type="radio" name="select_option" class="select_option" value="<?=$row_id;?>">No
I need radio button value along with user clicked on which radio button. how to achieve this? Can anyone please guide me.
I have added my class names(all, yes, no) in those html elements
<input type="radio" name="select_option" class="select_option all" value="<?=$row_id;?>">All
<input type="radio" name="select_option" class="select_option yes" value="<?=$row_id;?>">Yes
<input type="radio" name="select_option" class="select_option no" value="<?=$row_id;?>">No
Using jQuery
$(document).ready(function(){
$("input:radio").click(function(e){
if($(this).hasClass("all"))
{
console.log("which button -> all");
console.log("value="+$(this).val());
}
else if($(this).hasClass("yes"))
{
console.log("which button -> yes");
console.log("value="+$(this).val());
}
else if($(this).hasClass("no"))
{
console.log("which button -> no");
console.log("value="+$(this).val());
}
});
});
FIDDLE
Please add an extra parameter for storing the 'id' inside the input box, just like this:
<input type="radio" name="select_option" class="select_option" value="all" data-id="<?=$row_id;?>">All
<input type="radio" name="select_option" class="select_option" value="yes" data-id="<?=$row_id;?>">Yes
<input type="radio" name="select_option" class="select_option" value="no" data-id="<?=$row_id;?>">No
Now, here is the script which will run after checking the radio button:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.select_option').click(function() {
if ($(this).prop('checked')) {
var id = $(this).data('id');
var value = $(this).val();
}
alert(value);
});
});
</script>
I hope, this may be useful to you.
try this
$(".select_option").change(function(){
var radioValue = $("input[name='select_option']:checked").val();
if(radioValue){
alert("Your are clicked - " + radioValue);
}
});
$(".select_option").change(function () {
if ($(this).is(":checked")) {
var value = $(this).val();
console.log(value);
}
});
fiddle

Javascript - If no radio buttons are selected, check the first one

I'm a beginner in JavaScript. I have several radio buttons on my dynamic page and I want to create a script to make the following:
HTML:
<input type="radio" id="elemainfoto">
<input type="radio" id="elemainfoto">
<input type="radio" id="elemainfoto">
JavaScript:
var radio = '#elemainfoto',
if(radd.value == 0) {
radd.checked the first radio element,
} else {
keep the way it is,
}
If none of the radio elements are marked, mark the first compulsory.
I your expectation is that the first item get selected by default, then you should use HTML and not javascript for that and please note that you should not use two HTML elements with the same id in your case you should either replace by a class and/or add unique Ids for elements.
<input type="radio" class="elemainfoto" id="item1" checked>
<input type="radio" class="elemainfoto" id="item2">
<input type="radio" class="elemainfoto" id="item3>
Updated the answer based on RobG comment.
Something like this in pure JS (I changed ids to classes id should be unique):
var radio = document.querySelectorAll('.elemainfoto'),
checked = false;
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
checked = true;
break;
}
}
if (!checked) {
radio[0].checked = true;
}
else {
alert('something is checked')
}
A little shorter with jQuery:
var $radio = $('.elemainfoto');
if (!$radio.filter(':checked').length) {
$radio[0].checked = true;
}
else {
alert('something is checked')
}
using 'id' attribute in html with the same value more than once is invalid, you should use "name" for an input.
HTML:
<input type="radio" name="elementinfoto" value="1" />
<input type="radio" name="elementinfoto" value="2" />
<input type="radio" name="elementinfoto" value="3" />
JavaScript:
var radio = document.getElementsByName('elementinfoto'); // get all radio buttons
var isChecked = 0; // default is 0
for(var i=0; i<radio.length;i++) { // go over all the radio buttons with name 'elementinfoto'
if(radio[i].checked) isChecked = 1; // if one of them is checked - tell me
}
if(isChecked == 0) // if the default value stayed the same, check the first radio button
radio[0].checked = "checked";
example: http://jsfiddle.net/yxm4N/2/
A radio button group is formed by giving radio buttons the same name. An ID is optional and usually not necessary. If an ID is provided, each should have a different value. And the buttons should have a value so that there's a point to their existence.
To have one button selected by default, simply set the chosen button's checked attribute:
<form id="foo">
<input type="radio" name="elemainfoto" valu="0" checked>0<br>
<input type="radio" name="elemainfoto" valu="1">1<br>
<input type="radio" name="elemainfoto" valu="2">2<br>
<input type="reset">
</form>
Now if no other button is selected, or the form is reset, one button will be selected. Note that if you do not set a button as the default selected, then once a user checks a button, the only way to deselect it is to select a different radio button in the same group, or use a reset button (if provided).
If you want to set the default checked button in script, there are a couple of options. One is:
var buttons = document.getElementsByName('elemainfoto');
buttons[0].defaultChecked = true;
If you really want to check if one is selected, add a button like the following to the form:
<input type="button" value="Check buttons" onclick="checkButtons(this);">
Then the checkButtons function can be:
function checkButtons(el) {
var buttons;
var form = el && el.form;
if (form) {
buttons = form.elemainfoto;
for (var i=0, iLen=buttons.length; i<iLen; i++) {
// If a button is checked, return its value
if (buttons[i].checked) {
return buttons[i].value;
}
}
}
// Otherwise, try to check the first one and return undefined
buttons && buttons[0].checked;
}
you need to know how to use radio element. Id is unique in html page. you should assign same name for each radio element.
<input type="radio" name="elemainfoto" id="first" value="1" />
element 1
<input type="radio" name="elemainfoto" id="second" value="2" />
element 2
<input type="radio" name="elemainfotor" id="thrid" value="3" />
element 3
if you want to check the first radio button as default, set it in input tag attribute.
<input type="radio" name="elemainfoto" id="first" value="1" checked="true"/>
element 1
or you can do it with javascript also,
$("input:radio[name=elemainfoto]:first").attr('checked', true);
you can perform action for each radio button click, to know which item is checked
$(function(){
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
alert($(this).val());
}
});
});
if you want to perform a separate action for each radio button, try this below code
$(function () {
$('input[type="radio"]').click(function () {
if ($(this).is(':checked')) {
if ($(this).val() == '1') alert('first radio element is checked');
if ($(this).val() == '2') alert('second radio element is checked');
if ($(this).val() == '3') alert('third radio element is checked');
}
});
});
SEE THIS FIDDLE DEMO
Instead of selecting the first one, I prefered to use null
const radio = document.querySelectorAll('.timescale');
let timescale;
if (radio.checked) {
timescale = $('input[name=timescale_radio_buttons]:checked').val()
} else timescale = null;
You can write it like this with less code
HTML
<input type="radio" name="elementinfoto" value="1" />
<input type="radio" name="elementinfoto" value="2" />
<input type="radio" name="elementinfoto" value="3" />
JavaScript
const fields = document.getElementsByName('elementinfoto');
const value = fields.filter(el => el.checked).shift()?.value || null;
if(!value) {
fields.shift().checked = true;
}
You can replace the function shift() by [0] to get the first element if you prefer

using multiple sets of radio buttons, how can I unhide and hide images

Images //hide and show images with buttons
images are shown based on radio button/checkbox selected
<img id="storage_drawer" src="images/placeholder/get_hardware/storage_drawer.png" />
<img id="cash_drawer" src="images/placeholder/get_hardware/cash_drawer.png" />
Form two sets of radio buttons// changed into checkboxes by javascript function
<input type="checkbox" id="cashdrawer" name="type" value="cashDrawer" class="unique" >
<input type="checkbox" id="cashStorage" name="type" value="storageDrawer" class="unique">
//second set of radio buttons
<input type="checkbox" id="single" name="type2" value="singleLine" class="unique" >
<input type="checkbox" id="multi" name="type2" value="multiLine" class="unique" >
</form>
Start of script
$(document).ready(function(){
to make make checkboxes have the functionality of radio buttons
var $inputs = $(".unique");
$inputs.change(function(){
$inputs.not(this).prop('checked');
});
return false;
radio buttons -- first set of radio buttons
$("input[name$=type]").click(function(){
var value = $(this).val();
//Cash Drawers
if(value == 'cashDrawer') {
$("#cash_drawer").show();
$("#storage_drawer").hide();
}
else if( value == 'storageDrawer') {
$("#storage_drawer").show();
$("#cash_drawer").hide();
}
})
$("#cash_drawer").hide();
$("#storage_drawer").hide();
second set of radio buttons
$("input[name$=type2]").click(function(){
var value = $(this).val();
//Barcode Scanners
if(value = 'singleLine') {
$("#sinlgeBarcode").show();
$("#multiBarcode").hide();
}
else if(value == 'multiLine') {
$("#multiBarcode").show();
$("#sinlgeBarcode").hide();
}
})
$("#sinlgeBarcode").hide();
$("#multiBarcode").hide();
});
});
end of script
If your radio boxes have the same name attribute they will behave as radio buttons i.e only one selection can be active in the group, but if each button have their own name they can all be selected.
So if u have a collection of radios like this:
<form>
<input type="radio" name="1">
<input type="radio" name="2">
<input type="radio" name="3">
</form>
U can get them to behave like check boxes with a lil javascript:
// This will allow the radio boxes to toggle on of.
$("input[type=radio]").click(function(){
$(this).attr("checked", !$(this).attr("checked"));
});
Edit:
I did a js fiddler with a working example, maybe it will give some answers.
http://jsfiddle.net/uPp82/1/

Categories

Resources