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

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

Related

Uncheck checkbox when I check another one

Hey I have two issues with this following code.
First of all when I check the checkbox number 3 it automatically checks number 2, I only want that if I check it my self (Like when I check checkbox number 2).
The second issue is I can't uncheck a checkbox after checking it.
var cbs = document.getElementsByName("test");
function demo(obj) {
var hzp = cbs[1];
var ht = cbs[2];
for (var i = 0; i < cbs.length; i++) {
if(cbs[i].value == hzp.value || cbs[i].value === ht.value) {
if(cbs[i].value == obj.value) {
if(cbs[i].checked && hzp.checked || ht.checked) {
hzp.checked = true;
ht.checked = true;
}
}
}
cbs[i].checked = false;
}
obj.checked = true;
}
checkbox 1 <input type="checkbox" name="test" id="demo1" value="demo01" onClick="demo(this)">
checkbox 2 <input type="checkbox" name="test" id="demo2" value="demo02" onClick="demo(this)">
checkbox 3 <input type="checkbox" name="test" id="demo3" value="demo03" onClick="demo(this)">
checkbox 4 <input type="checkbox" name="test" id="demo" value="demo04" onClick="demo(this)">
e.target.value==cbs[0].value ?
if clicked input has value of demo01
cbs[3].checked=false
set demo04 checked to false
: e.target.value==cbs[3].value
else if clicked input has value of demo04
? cbs[0].checked=false
set demo01 checked to false
: null
else, nothing...
var cbs = document.getElementsByName("test")
cbs.forEach( test => {test.addEventListener("change", (e) => {
e.target.value==cbs[0].value ? cbs[3].checked=false : e.target.value==cbs[3].value ? cbs[0].checked=false : null
})
})
checkbox 1 <input type="checkbox" name="test" id="demo1" value="demo01" >
checkbox 2 <input type="checkbox" name="test" id="demo2" value="demo02">
checkbox 3 <input type="checkbox" name="test" id="demo3" value="demo03">
checkbox 4 <input type="checkbox" name="test" id="demo" value="demo04">
Look closely - this is not jQuery.
This gets your bigger job simplified - that of making the checkboxes work like radio buttons. Now, you should be able to quite easily add logic to make it do the rest of what you want.
The basic idea is to:
a. Trap when any checkbox is clicked
b. Store the checked checkbox value
c. Cache the checkbox itself (so we can turn it back on)
d. Uncheck ALL checkboxes
e. Re-check the one the user just checked.
f. Update div / variable with the stored value
Now, just add some additional (e.g. storedVal) variables to keep track of additional checkboxes.
const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);
var storedVal = '';
$$('input').forEach((el) => {
el.addEventListener('click', function(e){
storedVal = e.target.value;
let ckcb = e.target;
uncheckAll();
ckcb.checked = true;
console.log(storedVal);
$('#msg').innerText = storedVal;
});
});
const uncheckAll = () => {
$$('input').forEach((el) => {
el.checked = false;
});
}
#msg{
position:absolute;
top:70px;
right:30px;
font-size:2rem;
padding:10px;
background:wheat;
}
checkbox 1 <input type="checkbox" name="test" id="demo1" value="demo01">
checkbox 2 <input type="checkbox" name="test" id="demo2" value="demo02">
checkbox 3 <input type="checkbox" name="test" id="demo3" value="demo03">
checkbox 4 <input type="checkbox" name="test" id="demo" value="demo04">
<div id="msg"></div>

How find empty input value in jquery

I have two checkboxes the one checkbox value is 1 and the second one is 0.
One checkbox is for enabling and other for disabling. Now I want to identify when a user clicks on Disable checkbox How I will get Disable checkbox value and if a user clicks on Enable box then how I will get Enable Checkbox value
<input type="radio" name="forgot_pass" class="forgot_pass_enable" value="1" checked>
<input type="radio" name="forgot_pass" class="forgot_pass_disable" value="0">
I have tried This code but it's not working for me any help
$("body").on('change', '.forgot_pass_enable', function(event)
{
event.preventDefault();
/* Act on the event */
if($('.forgot_pass_enable').val().length > 0)
{
var status = 1;
console.log(status);
}
if($('.forgot_pass_disable').val().length > 0)
{
var status = 0;
console.log(statusasdad);
}
});
Neither of the elements you've shown are checkboxes - they are radio inputs.
To get the selected value apply the same class to both elements, then hook the change event to that class. Then you can simply read the value from it, like this:
$("body").on('change', '.forgot_pass', function(e) {
e.preventDefault();
var status = this.value;
console.log(this.value === '1' ? 'enabled' : 'disabled', status);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="radio" name="forgot_pass" class="forgot_pass" value="1" checked="checked">
<input type="radio" name="forgot_pass" class="forgot_pass" value="0">
If you did want to use a checkbox for this, which would be more applicable for an enable/disable switch, then the method is the same except you look for the checked property instead:
$("body").on('change', '.forgot_pass', function(e) {
e.preventDefault();
var status = this.checked ? '1' : '0'
console.log(status);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="checkbox" name="forgot_pass" class="forgot_pass" value="1" checked="checked">

Javascript: value of radio button to empty blank square box using innerHTML

I'm having trouble display value of radio button
when I click on the radio buttons,
I want to see all the values of buttons in the box.
its shows values on the console but in the box, it only shows 'carrot' which is one of ingredients in the array.
function mixRecipeBox(){
var mixIngredients = document.getElementsByTagName('input');
for(i=0; i<mixIngredients.length; i++){
if(mixIngredients[i].checked)
console.log(mixIngredients[i].value);
document.getElementById('mixbox').innerHTML = mixIngredients[i].value;
}
}
You are replacing all data of mixbox in each loop. use this to
append data.
You forgot {} for if block
Empty mixbox on start of function.
use checkbox instead of radio so user can discard choice.
function mixRecipeBox(){
document.getElementById('mixbox').innerHTML=""
var currentHTML;
var mixIngredients = document.getElementsByTagName('input');
for(i=0; i<mixIngredients.length; i++){
if(mixIngredients[i].checked)
{
console.log(mixIngredients[i].value);
currentHTML= document.getElementById('mixbox').innerHTML;
document.getElementById('mixbox').innerHTML = currentHTML+mixIngredients[i].value;
}
}
}
<input type="checkbox" value="1" onchange="mixRecipeBox()">
<input type="checkbox" value="2" onchange="mixRecipeBox()">
<input type="checkbox" value="3" onchange="mixRecipeBox()">
<input type="checkbox" value="4" onchange="mixRecipeBox()">
<div id="mixbox"></div>
Loop over each radio element and assign a click event handler.
The radio button click handler first clears the mixbox, then loops over each radio element and puts checked radio button values in the mixbox.
<div id="rads">
<input type="radio" value="one" />1
<input type="radio" value="two" />2
<input type="radio" value="three" />3
</div>
<div id="mixbox"></div>
<script>
var rads = document.querySelectorAll('#rads input[type=radio]');
var mixbox = document.getElementById('mixbox');
Array.prototype.forEach.call(rads, function (elem) {
elem.addEventListener('click', function (evt) {
mixbox.innerHTML = '';
Array.prototype.forEach.call(rads, function (ele) {
if ( ele.checked ) { mixbox.innerHTML += ele.value + '<br>'; }
})
})
})
</script>
JSFiddle

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/

make checkbox behave like radio buttons with javascript

I need to manipulate the behavior of the check boxes with javascript. They should basically behave like radio buttons (only one selectable at a time, plus unselect any previous selections).
The problem is that I can't use plain radio buttons in first place, because the name attribute for each radio button would be different.
I know its not the ultimate and shiniest solutions to make an apple look like a pear, and w3c wouldn't give me their thumbs for it, but it would be a better solution right now than to change the core php logic of the entire cms structure ;-)
Any help is much appreciated!
HTML :
<label><input type="checkbox" name="cb1" class="chb" /> CheckBox1</label>
<label><input type="checkbox" name="cb2" class="chb" /> CheckBox2</label>
<label><input type="checkbox" name="cb3" class="chb" /> CheckBox3</label>
<label><input type="checkbox" name="cb4" class="chb" /> CheckBox4</label>
jQuery :
$(".chb").change(function() {
$(".chb").prop('checked', false);
$(this).prop('checked', true);
});
if you want user can unchecked selected item :
$(".chb").change(function() {
$(".chb").not(this).prop('checked', false);
});
Demo :
http://jsfiddle.net/44Zfv/724/
There are many ways to do this. This is a clickhandler (plain js) for a div containing a number of checkboxes:
function cbclick(e){
e = e || event;
var cb = e.srcElement || e.target;
if (cb.type !== 'checkbox') {return true;}
var cbxs = document.getElementById('radiocb')
.getElementsByTagName('input'),
i = cbxs.length;
while(i--) {
if (cbxs[i].type
&& cbxs[i].type == 'checkbox'
&& cbxs[i].id !== cb.id) {
cbxs[i].checked = false;
}
}
}
Here's a working example.
This is a better option as it allows unchecking also:
$(".cb").change(function () {
$(".cb").not(this).prop('checked', false);
});
I kept it simple...
<html>
<body>
<script>
function chbx(obj)
{
var that = obj;
if(document.getElementById(that.id).checked == true) {
document.getElementById('id1').checked = false;
document.getElementById('id2').checked = false;
document.getElementById('id3').checked = false;
document.getElementById(that.id).checked = true;
}
}
</script>
<form action="your action" method="post">
<Input id='id1' type='Checkbox' Name ='name1' value ="S" onclick="chbx(this)"><br />
<Input id='id2' type='Checkbox' Name ='name2' value ="S" onclick="chbx(this)"><br />
<Input id='id3' type='Checkbox' Name ='name3' value ="S" onclick="chbx(this)"><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
#DJafari's answer doesn't let unchecking the checkbox. So I've updated it like this:
$(".chb").change(function(e) {
//Getting status before unchecking all
var status = $(this).prop("checked");
$(".chb").prop('checked', false);
$(this).prop('checked', true);
//false means checkbox was checked and became unchecked on change event, so let it stay unchecked
if (status === false) {
$(this).prop('checked', false);
}
});
https://jsfiddle.net/mapetek/nLtb0q1e/4/
Just in case it helps someone else
I was having the same situation where my client needed to have a checkbox behaving like a radio button. But to me it was meaningless to use a checkbox and make it act like radio button and it was very complex for me as I was using so many checkboxes in a GridView Control.
My Solution: So, I styled a radio button look like a checkbox and took the help of grouping of radio buttons.
You could give the group of checkboxes you need to behave like this a common class, then use the class to attach the following event handler:
function clickReset ()
{
var isChecked = false,
clicked = $(this),
set = $('.' + clicked.attr ('class') + ':checked').not (clicked);
if (isChecked = clicked.attr ('checked'))
{
set.attr ('checked', false);
}
return true;
}
$(function ()
{
$('.test').click (clickReset);
});
Note: This is pretty me just shooting from the hip, I've not tested this and it might need tweaking to work.
I would advise that you do look into finding a way of doing this with radio buttons if you can, as radios are the proper tool for the job. Users expect checkboxes to behave like checkboxes, not radios, and if they turn javascript off they can force through input into the server side script that you weren't expecting.
EDIT: Fixed function so that uncheck works properly and added a JS Fiddle link.
http://jsfiddle.net/j53gd/1/
<html>
<body>
<form action="#" method="post">
Radio 1: <input type="radio" name="radioMark" value="radio 1" /><br />
Radio 2: <input type="radio" name="radioMark" value="radio 2" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Ultimately you can use brackets with the name attribute to create an array of radio input like so:
<input type="radio" name="radioMark[]" value="radio1" />Radio 1
<input type="radio" name="radioMark[]" value="radio2" />Radio 2
<input type="radio" name="radioMark[]" value="radio3" />Radio 3
<input type="radio" name="radioMark[]" value="radio4" />Radio 4
What matters to transfer in the end are whats in the value attribute. Your names do not have to be different at all for each radio button. Hope that helps.
In Simple JS.
Enjoy !
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function onChoiceChange(obj) {
// Get Objects
var that=obj,
triggerChoice = document.getElementById(that.id),
domChoice1 = document.getElementById("Choice1"),
domChoice2 = document.getElementById("Choice2");
// Apply
if (triggerChoice.checked && triggerChoice.id === "Choice1")
domChoice2.checked=false;
if (triggerChoice.checked && triggerChoice.id === "Choice2")
domChoice1.checked=false;
// Logout
var log = document.getElementById("message");
log.innerHTML += "<br>"+ (domChoice1.checked ? "1" : "0") + ":" + (domChoice2.checked ? "1" : "0");
// Return !
return that.checked;
}
</script>
</head>
<body>
<h1 id="title">Title</h1>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice1" />Choice #1</label>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice2" />Choice #2</label>
<hr>
<div id="message"></div>
</body>
</html>
try this
<form id="form" action="#">
<input name="checkbox1" type="checkbox" />
<input name="checkbox2" type="checkbox" />
<input name="checkbox3" type="checkbox" />
<input name="checkbox4" type="checkbox" />
<input name="checkbox5" type="checkbox" />
<input name="checkbox6" type="checkbox" />
<input name="checkbox7" type="checkbox" />
<input name="checkbox8" type="checkbox" />
<input name="checkbox9" type="checkbox" />
<input name="checkbox10" type="checkbox" />
<input type="submit" name="submit" value="submit"/>
</form>
and this is the javascript
(function () {
function checkLikeRadio(tag) {
var form = document.getElementById(tag);//selecting the form ID
var checkboxList = form.getElementsByTagName("input");//selecting all checkbox of that form who will behave like radio button
for (var i = 0; i < checkboxList.length; i++) {//loop thorough every checkbox and set there value false.
if (checkboxList[i].type == "checkbox") {
checkboxList[i].checked = false;
}
checkboxList[i].onclick = function () {
checkLikeRadio(tag);//recursively calling the same function again to uncheck all checkbox
checkBoxName(this);// passing the location of selected checkbox to another function.
};
}
}
function checkBoxName(id) {
return id.checked = true;// selecting the selected checkbox and maiking its value true;
}
window.onload = function () {
checkLikeRadio("form");
};
})();
I like D.A.V.O.O.D's Answer to this question, but it relies on classes on the checkbox, which should not be needed.
As checkboxes tend to be related in that they will have the same (field) name, or a name which make them part of an array, then using that to decide which other checkboxes to untick would be a better solution.
$(document)
.on('change','input[type="checkbox"]',function(e){
var $t = $(this);
var $form = $t.closest('form');
var name = $t.attr('name');
var selector = 'input[type="checkbox"]';
var m = (new RegExp('^(.+)\\[([^\\]]+)\\]$')).exec( name );
if( m ){
selector += '[name^="'+m[1]+'["][name$="]"]';
}else{
selector += '[name="'+name+'"]';
}
$(selector, $form).not($t).prop('checked',false);
});
This code on jsFiddle

Categories

Resources