I have some radio buttons on a page, and I need to just identify which one was checked in my JS, based on ID. I'm not sure why this isn't working. Each time, I get the "nothing checked" message in my console. Thanks!
HTML:
<input type="radio" id="aud1">elephant</input>
<input type="radio" id="aud2">prairie dog</input>
<input type="radio" id="aud3">tiger</input>
JS:
var aud;
if (document.getElementById('aud1').checked) {
var aud = document.getElementById('file1');
}else if(document.getElementById('aud2').checked) {
var aud = document.getElementById('file2');
}else if (document.getElementById('aud3').checked){
var aud = document.getElementById('file3');
}
else console.log('nothing checked');
See below. I've added a button to your code that you can click after you have some checked.
Initially, when the page loads, there is nothing clicked. Your JS is ran as soon as the page is built there which is why you were seeing the nothing clicked.
document.getElementById('check-radios').onclick = function() {
var aud;
if (document.getElementById('aud1').checked) {
var aud = document.getElementById('file1');
console.log('aud1 checked');
}
else if (document.getElementById('aud2').checked) {
var aud = document.getElementById('file2');
console.log('aud2 checked');
}
else if (document.getElementById('aud3').checked) {
var aud = document.getElementById('file3');
console.log('aud3 checked');
}
else console.log('nothing checked');
}
<input type="radio" id="aud1">elephant</input>
<input type="radio" id="aud2">prairie dog</input>
<input type="radio" id="aud3">tiger</input>
<button id="check-radios">Check for clicked</button>
do you explicitly need this code? why not use a single class, and have the filename/desc as a custom attribute like so:
<input type="radio" name="animals" class="order" data-animal="elephant" />elephant
<input type="radio" name="animals" class="order" data-animal="zebra" />zebra
<input type="radio" name="animals" class="order" data-animal="lion" />lion
<script>
$(".order").click(function () {
var choice = this.getAttribute("data-animal");
alert(choice);
/* console.log(choice); */
})
</script>
That way you dont have to manually keep adding more code, u can just add the html at the top using the same class and a different attribute value... much easier to maintain -
Also since you had an elseif i added a name to group them as individual radios as I presume you intended?
<input type="radio" name="animals" class="order" checked data-animal="zebra">zebra
bear in mind there is no closing tag for input tags - just /> at the end instead of >
Related
I've searched all the web about it but i couldn't find a solution in javascript without jquery. The problem is the following: I have an entire array of radio elements, which should be checked or unchecked depending on database data. And this is accomplished. Now i have to make the radio button "uncheckable" to change the database data through the form.
I tried to make it in plain javascript as i don't want to think about frontend libraries for the moment.
The html is the following:
<td>
<input class="graphs" name="g4" value="S" defaultvalue="N" checked="true" type="radio">
</td>
<td>
<input class="graphs" name="g5" value="S" defaultvalue="N" type="radio">
The Javascript is the following:
<script type="text/javascript">
window.onload = (function(){
return function(){
var allRadios = document.getElementsByClassName('graphs');
var x = 0;
for(x = 0; x < allRadios.length; x++){
allRadios[x].onclick = function() {
if(this.checked == true){
this.checked = false;
}else{
this.checked = true
}
};
}
}})();
</script>
I've tried to debug and the result is always the same: the first if is executed and always true, even when the element is not checked.
I've tried the same script in jsfiddle and it works right. Is it a problem of my browser?
Thanks in advance.
this.checked == true in else block is not an assignment
If you want a radio to be uncheckable the you can disable it statically, you don't need to use any javascript.
For Unckecked disabled
<input type="radio" name="foo" value="N" disabled>
Four Checked disabled
<input type="radio" name="foo" value="N" checked disabled>
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();
}
});
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;
}
});