Autofill a radiobutton - javascript

I am trying to auto fill a radio button type, I was training on this website and used it's code to test it on my google chrome console, but it returns undefined.
The website : https://benalexkeen.com/autofilling-forms-with-javascript/
the html: view-source:https://benalexkeen.com/autofilling-forms-with-javascript/
I'm trying to tick the thrid radio button using this code:
var radioElements = document.getElementsByName("input3");
for (var i=0; i<radioElements.length; i++) {
if (radioElements[i].getAttribute('value') == 'Radio3') {
radioElements[i].checked = true;
}
}
output:
I tried to adapt this code to tick on another website and still have this undefined output

I hope this will help. You might be mistaken with the attribute value
var radioElements = document.getElementsByName("input3");
for (var i=0; i<radioElements.length; i++) {
if (radioElements[i].getAttribute('value') == 'radio3') {
radioElements[i].checked = true;
}
}
<input type="radio" id="radio1" name="input3" value="radio1">
<label for="radio1">Redio 1</label><br>
<input type="radio" id="radio2" name="input3" value="radio2">
<label for="radio2">Redio 2</label><br>
<input type="radio" id="radio3" name="input3" value="radio3">
<label for="radio3">Radio 3</label>

Here is another approach in case you want something easier to read IMO.
// Instead of var I used let.
let radioElements = document.getElementsByName("input3");
radioElements.forEach((input) => {
if(input.value === "Radio3") input.checked = true;
})
<input type="radio" id="Radio1" name="input3" value="Radio1">
<label for="radio1">Radio 1</label><br>
<input type="radio" id="Radio2" name="input3" value="Radio2">
<label for="radio2">Radio 2</label><br>
<input type="radio" id="radio3" name="input3" value="Radio3">
<label for="radio3">Radio 3</label>
And about undefined, if the code you are writing doesn't return anything, it will do that. Although, it doesn't mean is not working.

Related

How to Access A MC Question User Selection JS

how would I access the value of the radio mc choice (chosen by the user) through JS. For example, for this snippet from w3 schools
<input type="radio" id="html" name="fav_language" value="HTML">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="radio" id="javascript" name="fav_language" value="JavaScript">
<label for="javascript">JavaScript</label>
Please respond if you have an answer.
You can access the value of radio button by querySelector() method (There are other ways too). Add CSS for checked radio button in querySelector() method.
To avoid errors check if user selected any one of radio button. And then you're good to go.
let getValueBtn = document.getElementById("btn");
let output = document.getElementById("radioValue");
const getValue = () => {
const radioBtnValue = document.querySelector('input[type="radio"][name="fav_language"]:checked');
if(radioBtnValue === null) return `Nothing is Selected`;
return radioBtnValue.value;
}
getValueBtn.addEventListener("click", function() {
const radioValue = getValue();
output.innerText = radioValue;
});
<input type="radio" id="html" name="fav_language" value="HTML">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="radio" id="javascript" name="fav_language" value="JavaScript">
<label for="javascript">JavaScript</label>
<br>
<br>
<button id="btn">Get Value</button>
<p id="radioValue"></p>

radio buttons won't check / uncheck

I have some radio buttons in my web page.
when clicking the radio button it checks but when i click again it doesn't un-check.
i tried to add a JS function onclick
document.querySelectorAll('input[type="radio"]').forEach(x => x.addEventListener('click',function(){
if(this.checked == true){
this.checked = false;
}
else {
this.checked = true;
}
}))
when I added this method it allowed my to uncheck but didn't allow me to check any of them!
what can I be missing?
these are my checkboxes:
<input type="radio" id="name" name="name"><br>
<input type="radio" id="age" name="age"><br>
<input type="radio" id="email" name="email"><br>
They all have different name attribute values - therefore they can only be checked (because they're not comparing to another sibling radio value). I think you might be looking for type="checkbox" instead:
<input type="checkbox" id="name" name="name"><br>
<input type="checkbox" id="age" name="age"><br>
<input type="checkbox" id="email" name="email"><br>
Example: Hold down Ctrl (⌘ on mac) key to uncheck.
var radios = document.getElementsByTagName('input');
for(i=0; i<radios.length; i++ ) {
radios[i].onclick = function(e) {
if(e.ctrlKey || e.metaKey) {
this.checked = false;
}
}
}
<input type="radio" name="test" value="1" />
<input type="radio" name="test" value="2" checked="checked" />
<input type="radio" name="test" value="3" />
Use <input type="checkbox", not <input type="radio".
Radio button is used where you have to select one of some options (which must have same name).
For example,
<input type="radio" name="gender" id="male" value="male"> <br>
<input type="radio" name="gender" id="female" value="female"> <br>
<input type="radio" name="gender" id="other" value="other">
Know more about radio button and check boxes.
document.querySelectorAll('input[type="radio"]').forEach(x => x.addEventListener('click',function(){
if(this.value == 0){
this.checked = true;
document.querySelectorAll('input[type="radio"]').forEach(x=>x.value=0);
this.value = 1;
}
else {
this.checked = false;
document.querySelectorAll('input[type="radio"]').forEach(x=>x.value=0);
this.value = 0;
}
}))
<input type="radio" value="0" id="name" name="test"><br>
<input type="radio" value="0" id="age" name="test"><br>
<input type="radio" value="0" id="email" name="test"><br>
This code allows the user to deselect a radio button:
document.querySelectorAll('input[type="radio"]').forEach(x => x.addEventListener('click',function(){
if(! this.value0 || this.value0 == 0){
this.checked = true;
document.querySelectorAll('input[type="radio"][name="'+this.name+'"]').forEach(x=>x.value0=0);
this.value0 = 1;
} else {
this.checked = false;
document.querySelectorAll('input[type="radio"][name="'+this.name+'"]').forEach(x=>x.value0=0);
this.value0 = 0;
}
}))
It improves the answer of Sato Takeru.

Javascript not Un-Hiding Content

(I was unsure what title to use so i took what i felt described it if it doesnt fit please tell me/change it)
So i've been making this league of legends site for a while now and ran into a trouble.
I've been making a Filter menu that filters the "Champions"(Hero's) to only show those with the correct role/ability.
So i got an on-click script on checkboxes that should show the correct Champions when clicked on. but it doesnt seem to work.
When i uncheck the textbox it correctly takes back all of the champions, but when i "Check" it all champions disappears (should do this) but it doesnt show those wich apply to the filter. (I got all the correct id's on the DIV's, i know this since i have a search bar that works for filtering aswell but i want checkboxes for it since its simpler)
Checkboxes:
AD<input type="checkbox" name="adcarry" value="adcarry" id="check1" class="check1" onclick="boxchanged()">
AP<input type="checkbox" name="apcarry" value="apcarry" id="check2" class="check2" onclick="boxchanged()">
Carry<input type="checkbox" name="carry" value="carry" id="check3" class="check3" onclick="boxchanged()">
Tank<input type="checkbox" name="tank" value="tank" id="check4" class="check4" onclick="boxchanged()">
Support<input type="checkbox" name="support" value="support" id="check5" class="check5" onclick="boxchanged()">
Jungler<input type="checkbox" name="jungler" value="jungler" id="check6" class="check6" onclick="boxchanged()">
Burst<input type="checkbox" name="burst" value="burst" id="check7" class="check7" onclick="boxchanged()">
<button type="button" onclick="boxchanged()">Reset</button>
Affected divs are designed as following: (The classes changes depending on what the champion can do)
<div class="champion apcarry mid" id="ahri" onclick="OnClickChampion(this.id)"><img src="img/champions/ahri.jpg"> Ahri </div>
Script:
function boxchanged ( )
{
$("#num1").val("Search..");
if ($("[type='checkbox']:checked").length == 0)
{
$(".champion").show(200);
}
else
{
$(".champion").hide(200);
for (var i = 1;i < 7; i++)
{
var name = "check"+i;
console.log(name)
var name2 = document.getElementById(name);
console.log(name2)
if (name2.checked == true)
{
var name3 = name2.name;
$("."+name3).show();
}
}
}
};
You should stop any animation
$("."+name3).stop().show();
Here is your code much simplified
DEMO
$(function() {
$(".champion").on("click",function() {
// put OnClickChampion here
});
$(".check").on("click",function() {
$("#num1").val("Search..");
var checked = $("[type='checkbox']:checked");
console.log(checked.length);
if (checked.length == 0) {
$(".champion").stop().show(200);
}
else {
$(".champion").hide(200);
checked.each(function() {
var klass = $(this).val();
$("."+klass).stop().show(200);
});
}
});
});
using
<form>
<label for="check1">AD</label>
<input type="checkbox" value="adcarry" id="check1" class="check"/>
<label for="check2">AP</label>
<input type="checkbox" value="apcarry" id="check2" class="check"/>
<label for="check3">Carry</label>
<input type="checkbox" value="carry" id="check3" class="check"/>
<label for="check4">Tank</label>
<input type="checkbox"value="tank" id="check4" class="check"/>
<label for="check5">Support</label>
<input type="checkbox" value="support" id="check5" class="check"/>
<label for="check6">Jungler</label>
<input type="checkbox" value="jungler" id="check6" class="check"/>
<label for="check7">Burst</label>
<input type="checkbox" value="burst" id="check7" class="check"/>
<button type="reset" class="check">Reset</button>
</form>
<div class="champion apcarry mid" id="ahri"><img src="img/champions/ahri.jpg"> Ahri </div>
To show only the ones with more than one class
var klasses=[]
checked.each(function() {
klasses.push("."+$(this).val())
});
$(".champion").not(klasses.join(",")).stop().hide(200);

How do I get the value of the checked radio button?

I have this simple script attached to a questionnaire and am having a problem getting the selected answer to show up in a textarea. Here is the script:
function check() {
var complete = 0;
var total = 0;
for (i=0;i<document.form.length;i++)
{
if (document.form.elements[i].checked == true && complete < 10) {
complete++;
total = (total) + (Math.round(document.form.elements[i].value));
}
}
if (complete >= 10) {
document.form.message.value = document.form.question1.value;
}
}
And here is the HTML:
<input type="radio" value="1" name="question1" onclick="check()"> A<br />
<input type="radio" value="2" name="question1" onclick="check()"> B<br />
<input type="radio" value="3" name="question1" onclick="check()"> C<br />
<input type="radio" value="4" name="question1" onclick="check()"> D<br />
<input type="radio" value="1" name="question2" onclick="check()"> E<br />
<input type="radio" value="2" name="question2" onclick="check()"> F<br />
<input type="radio" value="3" name="question2" onclick="check()"> G<br />
<input type="radio" value="4" name="question2" onclick="check()"> H<br />
<textarea name="message"></textarea>
I would like the value to be returned, but I am getting undefined. If I alter the line in the script that returns the text to:
document.form.message.value = document.form.question1;
I get [object NodeList]. I know I am missing something so simple but for the life of me I cannot find it.
Also, is it possible I can return the letters A through H along with the value? I know I can replace the value with the letters but need the numbers there for calculations.
My answer is going under the assumption that you would like the <textarea> to be populated with text similar to:
User answered 1 for Question A
User answered 2 for Question F
To get the A or F passed back, I needed to modify your html in the following way:
<input type="radio" value="1" name="question1" onclick="check(this, 'A')"> A<br />
<input type="radio" value="2" name="question1" onclick="check(this, 'B')"> B<br />
<input type="radio" value="3" name="question1" onclick="check(this, 'C')"> C<br />
<input type="radio" value="4" name="question1" onclick="check(this, 'D')"> D<br />
<input type="radio" value="1" name="question2" onclick="check(this, 'E')"> E<br />
<input type="radio" value="2" name="question2" onclick="check(this, 'F')"> F<br />
<input type="radio" value="3" name="question2" onclick="check(this, 'G')"> G<br />
<input type="radio" value="4" name="question2" onclick="check(this, 'H')"> H<br />
<textarea name="message"></textarea>
Otherwise, there's no actual connection between the letter and the radio input.
Anyway, here's what I done did:
I noticed that each group was repeating the same functionality, so I created a single Object Constructor:
var Answer = function () {
this.text = '';
};
this.text will contain the special answer string per group.
Now let's create the two answer group objects:
var answerOne = new Answer();
var answerTwo = new Answer();
Next comes the check() function where we pass the input element as well as it's associated answer character:
var check = function (_input, _question) {
if (_input.name === "question1") {
answerOne.text = "User answered " + _input.value + " for Question " + _question + "\n";
}
if (_input.name === "question2") {
answerTwo.text = "User answered " + _input.value + " for Question " + _question + "\n";
}
document.getElementsByName('message')[0].value = answerOne.text + answerTwo.text;
};
Now, as the user selects an answer, the appropriate answer group's string gets updated accordingly without affecting the other group's answer string.
Here's a jsfiddle with it working: http://jsfiddle.net/smokinjoe/uC76f/13/
Hope that helps!
You are referencing a form element in your script, do you define a form?
The answer seems to be addressed here
Attach event listener through javascript to radio button
Because it's a radio button, you need to loop through all values to find the one that has been selected. Something like this should work:
for (var i=0; i < document.form.question1.length; i++)
{
if (document.form.question1[i].checked)
{
document.form.message.value = document.form.question1[i].value;
}
}
}
Here you go the complete solution.
Couple of things went wrong in your code.
1. The way you get values from radio group. You need to iterate and find out which is checked
2. Setting value to textarea. You need to do getElemenetsByName[x]
<script>
function check() {
var complete = 0;
var total = 0;
var x = document.getElementsByTagName('input');
for(var k=0;k<x.length;k++){
if (x[k].checked && complete < 10) {
complete++;
total = total + Math.round(x[k].value);
}
}
(document.getElementsByName('message')[0]).value = total;
}
</script>
<input type="radio" value="1" name="question1" onclick="check()"> A<br />
<input type="radio" value="2" name="question1" onclick="check()"> B<br />
<input type="radio" value="3" name="question1" onclick="check()"> C<br />
<input type="radio" value="4" name="question1" onclick="check()"> D<br />
<input type="radio" value="1" name="question2" onclick="check()"> E<br />
<input type="radio" value="2" name="question2" onclick="check()"> F<br />
<input type="radio" value="3" name="question2" onclick="check()"> G<br />
<input type="radio" value="4" name="question2" onclick="check()"> H<br />
<textarea name="message"></textarea>
Not tested this, and as I don't know the name (or id) of your form(s), or indeed how many forms you have in your document, I have referenced your form by it's id.
function check() {
var complete = 0;
var total = 0;
var formId = 'EnterYourFormId'; // This could be passed as a paramter to the function instead (e.g. "function check(formId) {")
var _from = document.getElementById(formId); // The form could also be referenced by it's index, e.g. document.forms[0]
for (i=0; i < _from.elements.length; i++) {
if (_from.elements[i].type=='checkbox' && _from.elements[i].checked && complete < 10) {
complete++;
total = total + parseInt(_from.elements[i].value);
}
}
if (complete >= 10) {
_form.message.value = _form.question1.value;
}
}

How to find the value of a radio button with pure javascript?

<input checked=checked type="radio" name="colors" value="red" />Red
<input type="radio" name="colors" value="green" />Green
<input type="radio" name="colors" value="blue" />Blue
Given the above, I set the red button to be selected by default (so I give it the checked=checked attribute. With this, if I ever call .checked on that input element, it will always return true, even if another option is selected.
In plain javascript (no jQuery), how can you get the actual selected option?
Try this:
var options = document.getElementsByName("colors");
if (options) {
for (var i = 0; i < options.length; i++) {
if (options[i].checked){
alert(options[i].value);
}
}
}
Would be so much easier with jQuery though... just saying.
I believe you will find it in the document.all collection:
var selectedColor = document.all["colors"];
plain javasript:
document.querySelector('input[name=colors]:checked').value;
you can try like this .....
This is example
<form name="frmRadio" method="post">
<input name="choice" value="1" type="radio" />1
<input name="choice" value="2" type="radio" />2
<input name="choice" value="3" type="radio" />3
<input name="choice" value="4" type="radio" />4
</form>
function to get the selected value
<script language="JavaScript">
function getRadioValue() {
for (index=0; index < document.frmRadio.choice.length; index++) {
if (document.frmRadio.choice[index].checked) {
var radioValue = document.frmRadio.choice[index].value;
break;
}
}
}
</script>
Well, they all have the same name. So naturally at least one of them has to be selected. Give them different ID's and try again.

Categories