let tile = document.getElementById("tile")
//see if a button is checked by creating a loop to iterate through the radio buttons
for (let i = 0; i < document.forms.choice.length; i++) {
if (document.forms.choice[i].checked ) { //form.choice = returns an array of the radio buttons
//checked returns a boolean if the button is checked or not; ask if the button is clicked or not and if it is follow this new loop
for (let i = 0; i < document.forms.choice.length; i++) { //this new loop iterates and asks if the value is a certain color, and if it is change the background color
if (document.forms.choice[i].value === "blue") {
tile.style.backgroundColor = 'blue';
} else if (document.forms.choice[i].value === "erase") {
tile.style.backgroundColor = 'white';
}
}
}
}
So I'm trying to get the tile to change colors when it is hovered on depending on which option is selected. (For the example right now it's just set to change the background color for simplicity purposes although I still haven't figured out to do it onhover). So what I tried to do was iterate over the form group to see if anything is checked or not, and then if it is move on to a nested loop which asks if the value is a certain color. I feel like i have the logic down right, but nothing activates and I'm not sure what else i can do. But obviously there's a mistake I'm just not catching.
<form id="color-options" name="form">
<input type="radio" name="choice" value="blue">
<label for="blue">Blue</label>
<input type="radio" name="choice" value="">
<label for="rainbow">Rainbow</label>
<input type="radio" name="choice" value="white">
<label for="erase">Eraser</label>
<input type="radio" name="choice" value="user">
<label for="color-picker">Color Picker</label>
<input type="color" id="color-picker">
</form>
<div id="Sketch">
<div id="tile">
</div>
</div>
JSfiddle: https://jsfiddle.net/Jbautista1056/83scu1ra/2/
Related
The outcome I am after is that when a user sends keyboard focus to a radio button group and navigates to each radio button using the arrow keys, or, clicks a radio button with a pointing device (mouse), the data-attribute value for that radio button is set to an element (h2).
I have got this far , and am now stuck. I am using an ID for the example, however, I would prefer to use a class or the data-set="X".
The code below sets the first data-col value but not the second.
Thanks for any help as I learn so much from Stackoverflow. I need this in vanilla JS and not jQuery, sorry.
<p>
<label for="">The colour is Green
<input type="radio" name="bob" data-col="Green" data-set="Green" id="demo3">
</label>
<label for="">The colour is Blue
<input type="radio" name="bob" data-col="Blue" data-set="Blue" id="demo3">
</label>
</p>
<h2 id="chjkl"></h2>
document.getElementById('demo3').onclick = function changeClk() {
const setCol = document.querySelector('#demo3');
document.getElementById('chjkl').innerHTML = setCol.dataset.col
}
document.getElementById('demo3').onfocus = function changeFoc() {
const setCol = document.querySelector('#demo3');
document.getElementById('chjkl').innerHTML = setCol.dataset.col
}
Use the event.target to get the dataset.
In the example below I change the color of your h2 elements background. Note that I am passing the event into the function and calling the function in the eventListener.
Also rather than having two eventListeners, I add a class to the radio button and then query that using querySelectorAll(). Then run the nodeList through a loop and check the event.target when the eventListener is fired.
An issue with your code is you have more than one element with the same ID. You should not have more than one element with any unique ID. ID must be unique to only one single element.
let radio = document.querySelectorAll('.radio')
let target = document.getElementById('chjkl')
function changeColor(e) {
target.style.backgroundColor = e.target.dataset.col
target.textContent = e.target.dataset.col
}
radio.forEach(btn => {
btn.addEventListener('focus', changeColor)
})
#chjkl {
display: flex;
justify-content: center;
letter-spacing: 1.3rem;
}
<p>
<label for="">The colour is Green
<input type="radio" name="bob" data-col="Green" class="radio">
</label>
<label for="">The colour is Red
<input type="radio" name="bob" data-col="Red" class="radio">
</label>
<label for="">The colour is Blue
<input type="radio" name="bob" data-col="Blue" class="radio">
</label>
<label for="">The colour is Orange
<input type="radio" name="bob" data-col="Orange" class="radio">
</label>
</p>
<h2 id="chjkl"></h2>
I am trying to write a function that will show or hide an html element (contained in a div) using javascript. Right now I have 3 radio buttons (to eventually show/hide 3 elements depending on radio button selected, but right now I am just trying to hide one element (month) if year or week is selected, and to show it if month is selected. My html is:
<div id="setting">
<input type="radio" id="year" name="view" value="year"> year<br>
<input type="radio" id="month" name="view" value="month"> month<br>
<input type="radio" id="week" name="view" value="week"> week
</div>
<div id="cal">
(element here I am trying to show/hide)
</div>
My javascript is:
function defineSetting (){
var setting = document.getElementById('setting').checked;
if(setting =='year'){
document.getElementById("cal").style.display = "none";
}else if(setting =='month'){
document.getElementById("cal").style.display = "unset";
}else if(setting =='week'){
document.getElementById("cal").style.display = "none";
}
}
I am also not super experienced with javascript and am trying to figure out how to call the function (if it works). If it is in the document ready function will it run when the page is loaded or do i need to call it somewhere.
I think this is what you're going for. You want to add an event listener to the buttons, and pass the value of the input that's checked to the defineSetting() function that hides/shows your #cal element. I also simplified your test in defineSetting()
<div id="setting">
<input type="radio" id="year" name="view" value="year" class="setting"> year<br>
<input type="radio" id="month" name="view" value="month" class="setting"> month<br>
<input type="radio" id="week" name="view" value="week" class="setting"> week
</div>
<div id="cal">
(element here I am trying to show/hide)
</div>
<style>
.hidden { display: none; }
</style>
<script>
var inputs = document.getElementsByClassName('setting'),
setting;
for (var i = 0; i < inputs.length; i++) {
var el = inputs[i];
el.addEventListener('change', function() {
defineSetting(this.value);
})
}
function defineSetting(setting) {
if (setting == 'year' || setting == 'week') {
document.getElementById("cal").classList.add('hidden');
} else {
document.getElementById("cal").classList.remove('hidden');
}
}
</script>
This will help you out:
How to get value of selected radio button?
You are trying to get the checked value of a div element, but this element doesn't have that. The input element do have that property so that's where you can get it from.
I have a simple web form that uses JavaScript for building a POST statement. In Chrome, I can use a simple line of code...
var form = document.forms['myForm'];
var env = form.env.value;
The form itself looks like this...
<form name="myForm" action='JavaScript:xmlhttpPost("/path/to/some/pythoncode.py")'>
<input type="radio" name="env" id="env" value="inside">Inside
<input type="radio" name="env" id="env" value="outside" checked="checked">Outside
<input type="radio" name="env" id="env" value="both">Both
<input type="radio" name="env" id="env" value="neither">Neither
I have some text boxes on the form that I can use the same technique to find the value (
var name = form.fname.value
with a
<input type="text" name="fname" id="fname">
However, when I submit the form and build my post, the value for the radio buttons is always undefined. It works fine in Chrome, but nothing in IE or FireFox.
I tried var env = document.getElementById('env').value, but for some reason that always defaults to the first value (inside) no matter what I select. That method also does not return a value when using Chrome.
Is there something I'm missing for reading the checked value of a radio input in FF or IE?
Try this
function getValueFromRadioButton(name) {
//Get all elements with the name
var buttons = document.getElementsByName(name);
for(var i = 0; i < buttons.length; i++) {
//Check if button is checked
var button = buttons[i];
if(button.checked) {
//Return value
return button.value;
}
}
//No radio button is selected.
return null;
}
IDs are unique so you should not use the same ID for multiple items. You can remove the all the radio button IDs if you use this function.
You are using the same ID for multiple Elements, ID is unique for element on the page.
use different IDs.
edit: names can be the same. because then the radio buttons are as a group.
As stated, the IDs should be different to be valid, but you could accomplish this by eliminating the IDs all together and using just the input name:
var form = document.forms['myForm'];
var radios = form.elements["env"];
var env = null;
for(var i=0;i<radios.length;i++) {
if(radios[i].checked == true) {
env = radios[i].value;
}
}
<form name="myForm">
<input type="radio" name="env" value="inside">Inside
<input type="radio" name="env" ivalue="outside" checked="checked">Outside
<input type="radio" name="env" value="both">Both
<input type="radio" name="env" value="neither">Neither
</form>
Short & clear on ES-2015, for use with Babel:
function getValueFromRadioButton( name ){
return [...document.getElementsByName(name)]
.reduce( (rez, btn) => (btn.checked ? btn.value : rez), null)
}
console.log( getValueFromRadioButton('payment') );
<div>
<input type="radio" name="payment" value="offline">
<input type="radio" name="payment" value="online">
<input type="radio" name="payment" value="part" checked>
<input type="radio" name="payment" value="free">
</div>
You can try this:
var form = document.querySelector('form#myForm');
var env_value = form.querySelector('[name="env"]:checked').value;
I'm pretty new to JS and maybe this is a very banal questions but I still can't figure out what's wrong. I have this simple html code:
<span>1</span>
<input id="check1" type="radio" value="a1"/>
<span>2</span>
<input id="check2" type="radio" value="b2"/>
<span>3</span>
<input id="check3" type="radio" value="c3"/>
<span>4</span>
<input id="check4" type="radio" value="a4"/>
<span>5</span>
<input id="check5" type="radio" value="b5"/>
<input id="red" type="button" value="Go" onclick=""/>
What i would like to achieve is, based on the radio checked change the onclick property.
For example, if check1 and check2 are checked go to google.com, if check1 and check3 go to jsfiddle.net etcetera. So I wrote a simple Javascript:
window.onchange = function redirect(){
if (document.getElementById('check1').checked && document.getElementById('check2').checked) {
location.href='www.google.com';
// document.getElementById('red').onclick="www.google.com"
}
else if (document.getElementById('check1').checked && document.getElementById('check3').checked) {
location.href='www.jsfiddle.net';
// document.getElementById('red').onclick="window.open('www.jsfiddle.net')"
}
}
Here You can find a JS Fiddle.
What I thought to do was to set the onclick property like I did with an image, using getElementById and then setting his source, so I wrote document.getElementById('red').onclick="window.open('random page')" but for some reason that I can't understand it doesn't work.
Questions:
1) As you can see in my code i wrote a location.href='address' that obviously doen't wait for the user to click the button, so that's not a solution, how can I make this work?
2)Is there a way to make this piece of code more scalable? What I mean is, in the future if I want to add another radio, I would have to modify manually the code and insert another else if, I thought about something like:
var radio = document.getElementByName('radio') //not sure if this is the right getElement
for (var i=1; i<radio.lenght; i++){
if radio[i].checked{ //is this right?
for (var n=i+1; n<radio.lenght; n++){
if radio[n].checked{
document.getElementById('red').onclick="window.open('random page')"
}
}
}
Any suggestion to my code is welcome.
Try out this in JS Fiddle. It contains how you can listen the onclick event of a button and to get the checked value of a radio button.
HTML part:
<form action="">
<input type="radio" name="vehicle" value="Yes" id='yes'>Yes<br>
<input type="radio" name="vehicle" value="No" id='no'>No
</form>
<input id="red" type="button" value="let's go"/>
JS part:
document.getElementById('red').onclick = function() {
if (document.getElementById('yes').checked) {
alert('I have a Vehicle.');
} else if(document.getElementById('no').checked) {
alert('I don\'t have a Vehicle.');
} else {
alert('No answer.');
}
}
If you use radio buttons, and you want only one to be selectable to the user at a time you have to set the same name attribute to them.
You can also make use of the value property of radio buttons for storing the redirection URL.
Here is a more useful example for you.
HTML part:
<form action="">
<input type="radio" name='redirect' value='https://www.google.com/' id='google'>Google<br />
<input type="radio" name='redirect' value='http://www.jsfiddle.net/' id='jsFiddle'>JS Fiddle<br />
<input type="radio" name='redirect' value='https://www.facebook.com/' id='Facebook'>Facebook
</form>
<input id="red" type="button" value="let's go"/>
JS part:
document.getElementById('red').onclick = function() {
var options = document.getElementsByName('redirect'),
length = options.length,
i = 0;
for (i; i < length; i++) {
if (options[i].checked) {
window.open(options[i].value);
}
}
}
if (document.getElementById('check1').checked&&document.getElementById('check2').checked)
{
document.getElementById('red').onclick=function(){
window.location.href ='http://www.google.com';
};
}
This code binds the function to the onclick event of element with id='red'. So add a bunch of such conditions and change the onclick binding whenever any radio button is checked/unchecked.
What method would be best to use to selectively set a single or multiple radio button(s) to a desired setting with JavaScript?
Very simple
radiobtn = document.getElementById("theid");
radiobtn.checked = true;
the form
<form name="teenageMutant">
<input value="aa" type="radio" name="ninjaTurtles"/>
<input value="bb" type="radio" name="ninjaTurtles"/>
<input value="cc" type="radio" name="ninjaTurtles" checked/>
</form>
value="cc" will be checked by default, if you remove the "checked" non of the boxes will be checked when the form is first loaded.
document.teenageMutant.ninjaTurtles[0].checked=true;
now value="aa" is checked. The other radio check boxes are unchecked.
see it in action: http://jsfiddle.net/yaArr/
You may do the same using the form id and the radio button id. Here is a form with id's.
<form id="lizardPeople" name="teenageMutant">
<input id="dinosaurs" value="aa" type="radio" name="ninjaTurtles"/>
<input id="elephant" value="bb" type="radio" name="ninjaTurtles"/>
<input id="dodoBird" value="cc" type="radio" name="ninjaTurtles" checked/>
</form>
value="cc" is checked by default.
document.forms["lizardPeople"]["dinosaurs"].checked=true;
now value="aa" with id="dinosaurs" is checked, just like before.
See it in action: http://jsfiddle.net/jPfXS/
Vanilla Javascript:
yourRadioButton.checked = true;
jQuery:
$('input[name=foo]').prop('checked', true);
or
$("input:checkbox").val() == "true"
You can also explicitly set value of radio button:
<form name="gendersForm">
<input type="radio" name="gender" value="M" /> Man
<input type="radio" name="gender" value="F" /> Woman
</form>
with the following script:
document.gendersForm.gender.value="F";
and corresponding radio button will be checked automatically.
Look at the example on JSFiddle.
/**
* setCheckedValueOfRadioButtonGroup
* #param {html input type=radio} vRadioObj
* #param {the radiobutton with this value will be checked} vValue
*/
function setCheckedValueOfRadioButtonGroup(vRadioObj, vValue) {
var radios = document.getElementsByName(vRadioObj.name);
for (var j = 0; j < radios.length; j++) {
if (radios[j].value == vValue) {
radios[j].checked = true;
break;
}
}
}
Try
myRadio.checked=true
<input type="radio" id="myRadio">My radio<br>
$("#id_of_radiobutton").prop("checked", true);
I am configuring a radio button within a document fragment and tried using radiobtn.checked = true;.
That didn't work so I instead went with this solution:
radiobtn.setAttribute("checked", "checked");
This sets checked using name to cycle through the elements and a value check to set the desired element to true. I kept it as simple as possible, its pretty easy to put it into a function or a loop, etc.
variable 'nameValue' is the radio elements name value
variable 'value' when matched sets the radio button
Array.from( document.querySelectorAll('[name="' + nameValue + '"]') ).forEach((element,index) =>
{
if (value === element.value) {
element.checked = true;
} else {
element.checked = false;
}
});