Getting the ID of a radio button using JavaScript - javascript

Is there a way to get the ID of a radio button using JavaScript?
So far I have:
HTML
<input type="radio" name="fullorfirst" id="fullname" />
JavaScript
var checkID = document.getElementById(fullname);
console.log(checkID);
It outputs as null.
Essentially what I want to do is:
document.getElementById(fullname).checked = true;
...in order to change the radio button fullname to be checked on page load.

you should put fullname between quotes, since it's a string:
document.getElementById("fullname");

function checkValue() // if you pass the form, checkValue(form)
{
var form = document.getElementById('fullname'); // if you passed the form, you wouldn't need this line.
for(var i = 0; i < form.buztype.length; i++)
{
if(form.buztype[i].checked)
{
var selectedValue = form.buztype[i].value;
}
}
alert(selectedValue);
return false;
}
Hope this helps.

JavaScript Solution:
document.getElementById("fullname").checked = true;
Jquery Solution:
$("#fullname").prop("checked", true);

Related

How to identify the checked radio button by using getElementsByName?

I have a form fontVortMetodo, which I declared as
var fM = document.forms["fontVortMetodo"];
The user has the choice to submit the form to one of three PHP pages. I let him make the choice first by radio buttons with the name select. Then he should press a button, which fires the result of the form elements to the selected page.
For this firing I used the function
function destinu() {
if (fM.elements("select")[0].checked) {
fM.action = "private_php/Zamenhofa.php";
} else if (fM.elements("select")[1].checked) {
fM.action = "private_php/intereuropeco.php";
} else if (fM.elements("select")[2].checked) {
tutm = true;
fM.action = "private_php/tutmondeco.php";
}
}
There was this error:
TypeError: fM.elements("select")[0].checked is not a function".
Maybe I should try
var destiny = getElementsByName("select")
and then proceed with if (destiny[0].checked) or if (destiny[0].checked == true).
I don’t know jQuery, which somebody advised me to use, and also for JavaScript I have no reference text. Where can I find a good tutorial for jQuery, although I prefer to do everything by using JavaScript pure?
Using pure JS
Use dataset attribute to store the action.
Use this selector [name="select"]:checked to get the checked radio button.
document.querySelector('button').addEventListener('click', function(e)  {
e.preventDefault();
var checked = document.querySelector('[name="select"]:checked');
var action = checked.dataset.action;
var form = document.querySelector('#fontVortMetodo');
form.setAttribute('action', action);
var tutm = checked.dataset.tutm !== undefined;
console.log("Action: " + action);
console.log('Is tutm: '+ tutm);
//$form.submit(); // This is if you need to to submit the form.
});
<form id='fontVortMetodo' name='fontVortMetodo'>
<input type='radio' name='select' data-action="private_php/Zamenhofa.php">
<input type='radio' name='select' data-action="private_php/intereuropeco.php">
<input type='radio' name='select' data-action="private_php/tutmondeco.php" data-tutm='true'>
<button>Submit</button>
</form>

Undefined Input Value When Checking ByClassName

I am trying to find the value of an input by className using pure JavaScript. When I run similar code for and ID it works, but when I try with a class name it returns undefined. I am able to do this with jQuery but I want to achieve it with pure JavaScript to have a better understanding of the language. Thank you!
JAVASCRIPT
var input1 = document.getElementsByClassName("blank1");
var submit = document.getElementsByClassName("submit");
correctAnswer = 'hello';
submit[0].addEventListener('click', checkFillIn);
function checkFillIn(){
if ( input1[0].value === correctAnswer ){
console.log('correct!');
}else{
console.log('incorrect');
}
}
HTML
<p><input id="blank1" value="" type="text"></input></p>
Submit
Please add class attribute on your input element. See example below:
<input id="blank1" class="blank1" value="" type="text">
Of course, you wouldn't want to make the id same with the class attribute.
Ot returns undefined because you have an error in your syntax:
getElementsByClassName(blank1)
blank1 was the ID not the class
This should work:
var input1 = document.getElementById("blank1");
var submit = document.getElementsByClassName("submit");
correctAnswer = 'hello';
// submit is an array getElementsByClassName returns an array of elements
submit[0].addEventListener('click', checkFillIn);
function checkFillIn(){
if ( input1.value === correctAnswer ){
console.log('correct!');
}else{
console.log('incorrect');
}
}
<p><input id="blank1" value="" type="text"></input></p>
Submit
The error in your code is on line 1, where you get the first Element in javascript. It should be:
var input1 = document.getElementById("blank1");
This is because blank1 is an ID, not a class name.
Hope this helps!
you need to change var input1 = document.getElementsByClassName("blank1");to var input1 = document.getElementsById("blank1");or add class="blank1"to your input .

Could someone please explain a piece of Javascript code?

I am doing a project in school, and as part of that I had to include radio buttons in my html form. Below is the Javascript code which some parts I don't quite understand. The code works fine. Could someone plz give me an explanation of how the code works.
var check = false;
for (var i=0; i < document.ExamEntry.Level.length; i++)
{
if (document.ExamEntry.Level[i].checked)
{
var radiovalue = document.ExamEntry.Level[i].value;
check =true;
var usermessage=confirm("You have chosen: ".concat(radiovalue));
if(usermessage == false)
{
var radiovalue = "";
check = false;
}
}
}
<!--I understand the code below, its just some parts of the above code.
if (check ==false)
{
msg+="ERROR:You must select an entry level \n";
document.getElementById ('Levelcell'). style.color = "red";
result = false;
}
I added comments to help explain this:
var check = false;
// set a variable 'i' from 0 up to the ExamEntry level length (so for each radio)
// if there are 10 items, this code will run 10 times, each time with 'i' a different value from 0 to 9
for (var i=0; i < document.ExamEntry.Level.length; i++)
{
// is the radio button checked? If so, do the stuff inside. If not, skip this part
if (document.ExamEntry.Level[i].checked)
{
// set variable radiovalue to the value of the particular radio button
var radiovalue = document.ExamEntry.Level[i].value;
// set the check variable to true
check =true;
// ask the user to confirm the value and set usermessage based on confirmation
var usermessage=confirm("You have chosen: ".concat(radiovalue));
// if the user hits no on confirm, it will reset the radiomessage to blank and check to false
if(usermessage == false)
{
var radiovalue = "";
check = false;
}
}
}
All form elements are bound to the global HTML document variable. So somewhere on the page there must be a form with the name of ExamEntry:
<form name='ExamEntry' id='ExamEntry` ...
The next part refers to an element in the form. Since they are expecting a radio button, Level must be an input of type radio:
<label name="Level" id="1" type="radio" ....
<label name="Level" id="2" type="radio" ....
The loop iterates through all radio buttons. If the the button is checked, it grabs the checked value, and shows that message. If it does not find a checked button, then it displays an error message.

validate a dynamicnumber of checkboxes using javascript

I have some ASP code which presents any where from 1-any number of checkboxes (which are named the same) on the page. This validation does work however I think its a bit weak:
if (document.getElementById('selectedDocs').checked)
{
//this is here to handle the situation where there is only one checkbox being displayed
}
else
{
var checked = false;
var field = myForm.selectedDocs;
for(var j = 0; j < field.length; j++)
{
if(field[j].checked == true)
{
checked = true;
break;
}
}
if(!checked)
{
alert("You have not ticked any options. At least one must be selected to proceed!")
return false;
}
}
I was working with the code in the else block but this only works when there is more than one checkbox. It ignores the fact I have ticked the one single option when there is only one. So I placed the code inside the if section......Although it woks its a bit of a hack, can someone kindly improve it for me?
Thanking you...
Use:
var field = myForm.getElementsByName('selectedDocs');
This always returns a NodeList that you can iterate over.
If they are in a form and all have the same name, they can be accessed as a collection that is a property of the form. So given:
<form id="f0" ...>
<input type="checkbox" name="cb0" ...>
<input type="checkbox" name="cb0" ...>
<input type="checkbox" name="cb0" ...>
...
</form>
All the following return a reference to the form:
var form = document.getElementById('f0');
var form = document.forms['f0'];
var form = document.forms[0]; // if first form in document
and and all the following return a collection of the checkboxes named "cb0":
var checkboxes = form.cb0
var checkboxes = form['cb0'];
var checkboxes = form.elements.['cb0'];

document.form.submit(); won't submit in safari

I'm using a javascript function to submit my form. This works in every browser except safari and I can't figure out why
My javascript function looks like this
function submitForm() {
var selectBox = '';
sel_guide_options = document.subForm.sel_guides;
if (sel_guide_options.type == "select-multiple") {
for (var i = 0; i <sel_guide_options.options.length; i++) {
sel_guide_options.options[i].selected = true;
}
}
document.subForm.submit();
}
and in my form I use this
<input type="submit" name="btnSubmit" value="#modification_type# #page_item#" id="btnSubmit" onclick="submitForm();">
does document.subForm.sel_guides point to a select list?
if so I would revise your code to (presuming subForm is the name of your form):
function submitForm() {
var selectBox = '';
var sForm = document.forms['subForm'];
sel_guide = sForm.elements['sel_guides'];
if (sel_guide.type == "select-multiple") {
for (var i = 0; i <sel_guide.options.length; i++) {
sel_guide.options[i].selected = true;
}
}
sForm.submit();
}
I seemed to have fixed it using document.subForm['0'].submit();
instead of document.subForm.submit();
No idea why that would make a difference but its not giving me any problems now. Works on the other browsers too.
Try changing the form element from a type="submit" to type="button".
Both should work but it's worth a try.

Categories

Resources