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

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

Related

Add event listener after getting radio button value

i want to loop through the radio input and after getting the selected button run a function on it to get value from the radio tag ... but im having problem attaching the a function to run on the selected radio
for(var i=0;i<removeCartItemsButtons.length; i++){
var button= removeCartItemsButtons[i]
button.addEventListener('click',removeCartItem)//**like i did here**
}
var form= document.getElementsByClassName('product-form')[0]
form.addEventListener('submit', function(e){
e.preventDefault()
var selectedSize = document.getElementsByName('size')
for(var i=0;i<selectedSize.length; i++){
var size=selectedSize[i].checked
size.addEventListener('change',addToCartClicked)
}
}
<form class="product-form">
<div class="product-sizes">
<input type="radio" class="size" name="size" id="size1" value="34">
<label for="size1">34</label>
<input type="radio" class="size" name="size" id="size2" value="36">
<label for="size2">36</label>
<input type="radio" class="size" name="size" id="size3" value="38">
<label for="size3">38</label>
<input type="radio" class="size" name="size" id="size4" value="40">
<label for="size4">40</label>
<input type="radio" class="size" name="size" id="size5" value="42">
<label for="size5">42</label>
<input type="radio" class="size" name="size" id="size6" value="44">
<label for="size6">44</label>
</div>
<button class="btn-black" type="submit" >ADD TO CART</button>
</form>
I think you'd need to modify your JS code like below (sorry, I added semicolon to help me read better :-)
var form = document.getElementsByClassName('product-form')[0];
form.addEventListener('submit', function(e){
e.preventDefault();
var selectedSize = document.getElementsByName('size');
for(var i=0; i<selectedSize.length; i++){
var size=selectedSize[i].checked;
if(size === true) {
selectedSize[i].addEventListener('change', addToCartClicked);
}
}
});
If you're running the submit event handler then there's no point then in adding an event handler to an element on the form.
If you want to extract the value of a radiobutton you can do it with this one line of code:
let size = document.querySelector('input[name="temp"]:checked').value;
Once you have that value you can call whatever Javascript function you need:
function addToCartClicked(size) {
console.log("Size: "+size);
document.body.append(size);
}
var form = document.getElementsByClassName('product-form')[0];
form.addEventListener('submit', function(e){
e.preventDefault();
let size = document.querySelector('input[name="temp"]:checked').value;
addToCartClicked(size);
});
I don't know why you want to add event after the form is already submitted but anyway you can check for selected element and add your event
when the index of selected element come the size result will be true so you can add your event now
also you was added the event to size var who it true or false not for the input element
i changed your change event with click
Here's your code
var form= document.getElementsByClassName('product-form')[0]
form.addEventListener('submit', function(e){
e.preventDefault();
var selectedSize = document.getElementsByName('size');
for(var i=0; i<selectedSize.length; i++) {
var size= selectedSize[i].checked;
if(size) {
selectedSize[i].addEventListener('click',addToCartClicked);
}
}
});
function addToCartClicked() {
document.body.append(this.value);
}

How to get the text of the checked radio button? [duplicate]

This question already has answers here:
How do I get the label of the selected radio button using javascript
(3 answers)
Closed 8 years ago.
I have a group of radio buttons and want to get the checked radio button, then alert the text, not only the value of it. To explain more, when the user clicks the first radio button, and then submits the form, I want the browser to alert "Desktop Case." And I want to achieve this without jQuery.
<form action="" name="form1">
<label for="radio400">Desktop Case</label>
<input type="radio" name="rad_case" value="400" id="radio400"/>
<label for="radio401">Mini Tower</label>
<input type="radio" name="rad_case" value="401" id="radio401"/>
<label for="radio402">Full Tower</label>
<input type="radio" name="rad_case" value="402" id="radio402"/>
<input type="button" value="Submit" name="btn_submit" onclick="update_order_onclick()"/>
</form>
The following works for your example. It uses CSS selectors to target the checked input. Based on its id, the appropriate label is found:
function update_order_onclick() {
var value= 'Nothing selected',
selected= document.querySelector('input[name="rad_case"]:checked'),
selection= document.querySelector('#selection');
if(selected) {
value= document.querySelector('label[for="'+selected.id+'"]').innerHTML;
}
selection.innerHTML= value;
}
<form action="" name="form1">
<label for="radio400">Desktop Case</label>
<input type="radio" name="rad_case" value="400" id="radio400"/>
<br>
<label for="radio401">Mini Tower</label>
<input type="radio" name="rad_case" value="401" id="radio401"/>
<br>
<label for="radio402">Full Tower</label>
<input type="radio" name="rad_case" value="402" id="radio402"/>
<br>
<input type="button" value="Submit" name="btn_submit" onclick="update_order_onclick()"/>
</form>
<div id="selection"></div>
First, we create a function to loop through the radio buttons group we have, and checks if it is checked or not.
function get_radio_val(form, name)
{
var val;
var radios = form.elements[name];
for (var i =0; i < radios.length; i++)
{
if (radios[i].checked)
{
val = radios[i];
break;
}
}
return val;
}
Then we write the function that will be executed on onclick event.
function update_order_onclick()
{
var val = get_radio_val(document.form1, 'rad_case');
var val_id = val.id;
var selector = 'label[for=' + val_id + ']';
var label = document.querySelector(selector);
var label_text = label.innerHTML;
alert(label_text);
}
The thing that helped us here, is that the label for attribute has to be the same value as the radio button id and that's how we selected it in the function above.
simply do the following:
var checked = document.querySelector('input:checked');
var id = checked?checked.id:'bla';
var lab = document.querySelector('label[for='+id+']');
var lab_text = lab?lab.textContent:'';

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

how to get checked radio button value in javascript

I have some set of radio button. I am trying to get checked radio button value using java script. But I got the error of uncaught id. I do the following code in html 5. I am not getting the value.
function timeout()
{
if (document.getElementById["RadioButton1"].checked)
{
choice = document.getElementById["RadioButton1"].value;
alert('choice');
}
if (document.getElementById["RadioButton2"].checked)
{
choice = document.getElementById["RadioButton2"].value;
alert('choice');
}
if (document.getElementById["RadioButton3"].checked)
{
choice = document.getElementById["RadioButton3"].value;
alert('choice');
}
if (document.getElementById["RadioButton4"].checked)
{
choice = document.getElementById["RadioButton4"].value;
alert('choice');
}
var c = document.getElementById("label1").value;
}
If you use the same name(in same radio button group) for all radio buttons like this
<input type="radio" id="RadioButton1" name="radio_group" value="1"/>
<input type="radio" id="RadioButton2" name="radio_group" value="2"/>
<input type="radio" id="RadioButton3" name="radio_group" value="3"/>
you can get the selected(checked radio button value ) using jQuery,in one line.
var Val = $("input[name=radio_group]:checked").val();
A set of radio buttons should all have the same name. So get the set, find the checked one and read its value:
function getValue(name) {
var rbs = document.getElementsByName(name);
for (var i=0, iLen=rbs.length, i<iLen; i++) {
if (rbs[i].checked) {
return rbs[i].value;
}
}
}
If the controls are in a form (which the usually are) and you have a reference to the form, you can get the set using:
var rbs = formRef[name];
$(document).ready(function(){
$('#btnsubmit').click(function(){
var result = $('input[type="radio"]:checked');
if (result.length > 0) {
$('#result').html(result.val()+" is Checked");
}else{
$('#result').html(" No radio button is Checked");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<input type="submit" id="btnsubmit" value="submit">
<div id="result"></div>
The major problem visible from your code is a syntax error.
document.getElementById is a method and not an object, so you should call it with parens:
// --------------------v--------------v
document.getElementById("RadioButton1").value
This is ans for #yogi comment(
how we can implement same for checkboxes?)
$(document).ready(function(){
$('#btnsubmit').click(function(){
var result = $('input[type="checkbox"]:checked');
if (result.length > 0) {
var resultstring = result.length +"checkboxes checked <br>";
result.each(function(){
resultstring += $(this).val()+" <br>"; //append value to exsiting var
});
$('#result').html(resultstring);
}else{
$('#result').html(" No checkbox is Checked");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="checkbox" name="skill" value="Java"> Java
<input type="checkbox" name="skill" value="Jquery"> Jquery
<input type="checkbox" name="skill" value="PHP"> PHP
<input type="submit" id="btnsubmit" value="submit">
<div id="result"></div>

Radio button onChange function

I have a small problem. What is wrong with this function? I have no idea. I need pop-up alert window when the radio button is selected. Thanks for every reply.
HTML
<input type="radio" name="radioButton" class="choice" value="1">
<input type="radio" name="radioButton" class="choice" value="2">
<input type="radio" name="radioButton" class="choice" value="3">
JavaScript
var FormFields =
{
init: function()
{
var radio = document.getElementsByName("radioButton");
radio.onchange = FormFields.showAlert;
},
showAlert: function()
{
alert("Bye!");
},
};
Because getElementsByName returns a NodeList you'll need to apply the event callback to each input:
var radios = document.getElementsByName("radioButton");
for(var i = 0;i < radios.length;i++){
radios[i].onchange = FormFields.showAlert;
}
Demo: http://jsfiddle.net/louisbros/H7TdB/
getElementsByName gets a list of elements so you are calling onChange on the array. https://developer.mozilla.org/en-US/docs/DOM/document.getElementsByName
You want to loop through the elements and apply the onChange.

Categories

Resources