Accessing radio elements in forms in javascript - javascript

I have a use case where the the number of radio buttons can be 1 or more, what is the best practice to check
i.e
var radioElements = document.forms["formname"].elements["abc"];
for(var i=0; i < radioElements.length; i++) {
if(radioElements[i].checked) {
alert("blah..");
break;
}
}
This works when the DOM has
<form name="formname">
<input type=radio name=abc id=abc value=aaa/>
<input type=radio name=abc id=abc value=bbb/>
</form>
But fails to work when it has only one radio element
<form name="formname">
<input type=radio name=abc id=abc value=aaa/>
</form>
How can I make the above javascript work in both these cases.

You could use getElementsByName. This method always returns a collection which you can iterate over:
var radioElements = document.getElementsByName("abc");
for(var i=0; i < radioElements.length; i++)
{
if(radioElements[i].checked)
{
alert("blah..");
break;
}
}
See an example of this in action at jsfiddle.net/L6SKx/.

You're accessing the radio buttons wrong:
var radios = document.forms['formname'].abc;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert('#' + i + ' is checked, with value ' + radios[i].value);
}
}
As well, with your multiple radio button example, it's invalid to have the same ID on two or more separate DOM elements. An ID has to be unique on the page.

Related

Is it possible to use multiple for loop at same time?

I want to create a html form, it have 2 group(Name and fruit), each group have two check boxes, When user clicks the checkbox that input name are user_checkbox[] and fruit_checkbox[] , its will do something,i need to use array and for loop to get the user which group of checkboxes was checked , but it seems not to allow me use multiple for loop.
My Html File
//group1
<input name="user_checkbox[]" type="checkbox" value="Peter" onclick="showinputtext();" >Peter
<input name="user_checkbox[]" type="checkbox" value="Billy" onclick="showinputtext();" >Billy
//group2
<input name="fruit_checkbox[]" type="checkbox" value="Apple" onclick="showinputtext();" >Apple
<input name="fruit_checkbox[]" type="checkbox" value="Banner" onclick="showinputtext();" >Banana
My Javascript file
function showinputtext() {
var name = document.getElementsByName("user_checkbox[]");
var fruit = document.getElementsByName("fruit_checkbox[]");
for (var n = 0; n < name.length; n++) && for (var f = 0; f < fruit.length; f++) {
if(name[n].checked && fruit[f].checked){
dosomething..................
}
}
but it is not work for me, any idea?? thx
Try nested for loops.
function showinputtext(){
var name = document.getElementsByName("user_checkbox[]");
var fruit = document.getElementsByName("fruit_checkbox[]");
for (var i = 0; i < name.length; i++) {
for (var j = 0; j < fruit.length; j++) {
if(name[i].checked && fruit[j].checked){
alert("ok");
}
}
}
};
if you use jquery
try it :
Example
$("[type='checkbox']").on("click",function(){
var name = document.getElementsByName("user_checkbox[]");
var fruit = document.getElementsByName("fruit_checkbox[]");
for (var i = 0; i < name.length; i++) {
for (var j = 0; j < fruit.length; j++) {
if(name[i].checked && fruit[j].checked){
alert("ok");
}
}
}
});
Why not use forEach? Looks a bit nicer and does the same job in this instance:
function showInputText() {
var nameCheckboxes = document.getElementsByName("user_checkbox[]");
var fruitCheckboxes = document.getElementsByName("fruit_checkbox[]");
nameCheckboxes.forEach(function(nameCheckbox) {
fruitCheckboxes.forEach(function(fruitCheckbox) {
if (nameCheckbox.checked && fruitCheckbox.checked) {
alert ("ok");
};
});
});
I renamed the variables and the function to make this a bit more readable!
Just remember to change the function calls in the onclick attributes if you go for this approach:
// Group 1
<input name="user_checkbox[]" type="checkbox" value="Peter" onclick="showInputText();" >Peter
<input name="user_checkbox[]" type="checkbox" value="Billy" onclick="showInputText();" >Billy
// Group 2
<input name="fruit_checkbox[]" type="checkbox" value="Apple" onclick="showInputText();" >Apple
<input name="fruit_checkbox[]" type="checkbox" value="Banner" onclick="showInputText();" >Banana
However, reading your post, you might not need to do this at all. It seems unnecessary to iterate through both groups in a nested loop. Why not instead add each item to an array and "Do stuff" with both when the form is submitted?
I would change your checkboxes to have a fruit-input and user-input class:
<input type="checkbox" name="peter" class="user-input">
<input type="checkbox" name="banana" class="fruit-input">
Then I would add an event listener to the fruit-input and user-input elements which listen for changes to the checkboxes. When a change event occurs it then checks if the input has been checked or not, and it will then add or remove from either the selectedFruits or selectedUsers arrays:
document.getElementsByClassName("fruit-input")
.forEach(function(input){
input.addEventListener("change", selectFruit);
});
document.getElementsByClassName("user-input")
.forEach(function(input){
input.addEventListener("change", selectUser);
});
var selectedFruits = [];
var selectedUsers = [];
function selectFruit() {
var fruit = this.getAttribute("name");
if (this.checked) {
selectedFuits.push(fruit);
} else {
selectedFruits.remove(fruit);
}
}
function selectUser() {
var user = this.getAttribute("name");
if (this.checked) {
selectedUsers.push(user);
} else {
selectedUsers.remove(user);
}
}
Notice how the functions grab the value to add to the arrays from the input element's name attribute. Your current name attributes are invalid as they should really be unique.
It is even possible to refactor my suggestion above to have one generic input field listener and determine the array to add to based on a data attribute or something. But this is a good starting point.
After all this you can do whatever you need with the selectedFruits or selectedUsers arrays.
Try placing the second for loop inside the first one, like so
for (var n = 0; n < name.length; n++) {
for (var f = 0; f < fruit.length; f++) {
if(chboxsEng_single[n].checked && chboxsEng_fruit[f].checked){
dosomething..................
}
}
}
Be aware that this will go through every single value of f a total of n times, which may or may not be behaviour that you desire, it's not clear in the question.

Loop radio-button form javascript

I am trying to loop a radio-button form but with no success.
Despite the length of the form is 3 (same as number of radiobuttons) I can not access individual elements.
The purpose is to change the text. Its works If I want to access the first element:
var child = form.firstChild;
alert(child.nextSibling.nextSibling.nextSibling.innerHTML);
this returns the first radiobutton text.
But if I create a loop out of this
function getRadioBInfo() {
var form = document.getElementById("myform");
for (var i = 0; i < form.length; i++) {
var iForm = form[i];
var child = iForm.firstChild;
alert(child.nextSibling.nextSibling.nextSibling.innerHTML);
}
}
.. I get I TypeError: child is null
What is wrong with this code?
HTML
<form action="" name="deliver_form" id="myform" style="display: block;">
<input type="radio" name="delivering" id="radio1" value="deliver"> <label>label1</label><br>
<input type="radio" name="delivering" value="comeandtake"> <label>label2</label><br>
<input type="radio" name="delivering" value="express"> <label>label3</label>
</form>
I think you are looking for something like following.
var form = document.getElementById("myform");
for (var i = 0; i < form.length; i++) {
var child = form.getElementsByTagName('input')[i];
alert(child.nextSibling.nextSibling.innerHTML);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" name="deliver_form" id="myform" style="display: block;">
<input type="radio" name="delivering" id="radio1" value="deliver"> <label>label1</label><br>
<input type="radio" name="delivering" value="comeandtake"> <label>label2</label><br>
<input type="radio" name="delivering" value="express"> <label>label3</label>
</form>
Since you've tagged jquery, you could use:
$('[name=delivering']).each( function() {
alert( $(this).find('label').html() );
});
To get the label followed after the radio button you could try this:
function getRadioBInfo() {
var form = document.getElementById("myform");
var radios = form.querySelectorAll('input[type=radio]');
var i;
for (i = 0; i < radios.length; i++) {
var radio = radios[i];
console.log(radio.nextSibling.innerHTML);
}
}
getRadioBInfo();
pitfall: there shouldn't be whitespace between the radio or the button. Otherwise nextSibling returns text and not the label
demo
Why you are not getting by name
Try this
function getRadioBInfo() {
var arrRadioBtns = document.getElementsByName("delivering");
for (var i = 0; i < arrRadioBtns.length; i++) {
var btn = arrRadioBtns[i];
alert (btn.value);
}
}
Working Example
form[i] contains only radio buttons.If You want to take the labels Try using
var lbl = document.getElementsByTagName('label');
for (var i=0;i < lbl.length; i++){ lbl[i].innerHTML = 'radio' + i; }
and loop through the labels and change the text
Couple of observation
var form = document.getElementById("myform");
form will not be an array,Instead it will be a String,So you are iteration of the string.length;
You can use doucment.getElementsByName to get all radio buttons with common name
Hope this snippet will be useful
function getRadioBInfo() {
//Retun collection of radio button with same name
var _getRadio = document.getElementsByName("delivering");
// loop through the collection
for(var i = 0;i<_getRadio.length;i++){
//nextElementSibling will return label tag next to each radio input
console.log(_getRadio[i].nextElementSibling.innerHTML)
}
}
getRadioBInfo();
Jsfiddle

Submitting a 'input type="submit"' button using JavaScript with a Value and without ID or Name

I want to submit a button using JavaScript that looks like this:
<input type="submit" value=" somevalue ">
I was told that the web page is using jQuery but I have no clue.
Any suggestion ?
You can check for the inputs in the DOM that have type="submit" and then fire click() for it.
var elms = document.getElementsByTagName('input');
for(var i = 0; i < elms.length; i++) {
if(elms[i].type == "submit") {
elms[i].click();
break;
}
}
It would be easier to start from the parents though, like the form containing this input.
EDIT:
Alright, since there are many input type="submit" in the page and apparently we know nothing about the one we want to fire but its value is different from the other submits we can add the value check to the code as well:
var elms = document.getElementsByTagName('input');
for(var i = 0; i < elms.length; i++) {
var sb = elms[i];
if(sb.type == "submit" && sb.value == "YOUR_VALUE" ) {
sb.click();
break;
}
}

How to change the style of a radio button with javascript when clicked

I have an order form that has three sets of radio button options. Ultimately, I would like to have the text of the radio button in each group change to bold and red when it is clicked. However, I'm not having any luck just changing the color of even one group. Below is the loop I was using to try to change one group of radio buttons. My logic was to go through the group of radio buttons and if one of them were clicked it would change the style of the text. What am I doing wrong with this function?
function highlight() {
var radios = document.getElementsByName('cases');
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked == true) {
return document.getElementByName.style.color = 'red';
}
}
}
This is one group of radio buttons in my code. The other two groups are similar:
<input id="case1" type="radio" name="cases" value="500.00" onclick="highlight()"/> Desktop Case ($500.00) </br>
<input id="case2" type="radio" name="cases" value="600.00" onclick="highlight()"/> Mini-Tower Case ($600.00) </br>
<input id="case3" type="radio" name="cases" value="700.00" onclick="highlight()"/> Full-Tower Case ($700.00) </br>
Any help would be greatly appreciated.
If you amend your code, and wrap the text in a label element and, incidentally, you can't change the color or font-weight properties of text unless it's wrapped in an element, and that would have to be a separate element for each string of text you want to affect :
<input id="case1" type="radio" name="cases" value="500.00" onclick="highlight()"/><label for="case1">Desktop Case ($500.00)</label>
<input id="case2" type="radio" name="cases" value="600.00" onclick="highlight()"/><label for="case2">Mini-Tower Case ($600.00)</label>
<input id="case3" type="radio" name="cases" value="700.00" onclick="highlight()"/> <label for="case3">Full-Tower Case ($700.00)</label>
You can achieve this with just CSS:
input[type=radio]:checked + label {
color: red;
font-weight: bold;
}
JS Fiddle demo.
Incidentally, to use plain JavaScript I'd suggest:
function choiceHighlight(radio){
var groupName = radio.name,
group = document.getElementsByName(groupName);
for (var i = 0, len = group.length; i < len; i++){
group[i].nextSibling.className = group[i].checked ? 'chosen' : 'unchosen';
}
}
var radios = document.getElementsByName('cases');
for (var i = 0, len = radios.length; i < len; i++){
radios[i].addEventListener('change', function(){
choiceHighlight(this);
});
}
JS Fiddle demo.
Your return statement looks off:
return document.getElementByName.style.color = 'red';
Also note that you've attempted to give the radio inputs a color of red, but they cannot be styled in this way. The text that you have next to the inputs is not part of the input itself.
Here's a simplified script that gets you the input values onchange (not onselect). You should be able to use this as a better starting point: http://jsfiddle.net/rWp6E/
var radios = document.getElementsByName('cases');
for (var i = 0; i < radios.length; i++) {
radios[i].onchange = function () {
alert(this.value);
}
}
getElementByName isn't valid Javascript. A better way to do this would be to use the onCheckedChanged event to change your style:
<input id="case1" type="radio" name="cases" oncheckedchanged="highlight(this)" value="500.00"/>
<script type="text/javascript">
function highlight(e) {
if(e.checked == true)
{e.style.color = "red"}
else
{e.style.color = "some other color"}
}
Note that you will actually have to change the style of the label if you want to change the color of the text.
There is also a :checked selector in CSS3 (as someone else mentioned above), however it will not work in some older browsers, namely IE8 and earlier.

How do I validate a group of textboxes using javascript?

I have group of check-boxes and corresponding text-boxes with them. I can get each checkbox one by one, but how do I get the group of textboxes so I can validate them?
Here is my javascript code below:
function validate_orderform(proform)
{
var flag=0;
for (var i = 0; i < proform.chk.length; i++) {
if (proform.chk[i].checked && proform.quant[i].value=="") {
flag=1;
}
}
if(flag==1){
return false;
}
return true;
}
and my html code:
<td><input type="checkbox" id="chk1" name="chk"></td>
<td><input type="text" size="10" id="quant1" name="quant1"></td>...and so on
If name of textboxes are different then you can access all textboxes by
var txtObjList = document.getElementsByTagName("input");
for(var i=0; i < txtObjList.length; i++){
if(txtObjList[i].getAttribute("type") == "text" && this.value != ""){
// success for i+1 textbox
}
}
Or you can give common class name to all textboxes and then can access by
var txtObjList = document.getElementsByClassName("classname");
for(var i=0; i < txtObjList.length; i++){
if(this.value != ""){
// success for i+1 textbox
}
}
Remember by using javascript library such as jquery, prototype your work will be simpler.
There are a couple of methods you could use, you could use document.getElementsByTagName to retrieve all of the input elements, check their type etc... It works but it's slow and potentially expensive depending on how complex your form is.
If you have a group of checkboxes and each one has it's own text box then you could group them, so add a common name to each type, e.g.
Entry 1:
<input type="checkbox" id="chk1" name="chk"/>
<input type="text" id="quant1" name="quant"/>
Entry 2:
<input type="checkbox" id="chk2" name="chk"/>
<input type="text" id="quant2" name="quant"/>
Then you can use the document.getElementsByName method, so in this instance the following would retrieve a collection of 2 objects for you're text boxes:
var myTextBoxes = document.getElementsByName("quant");

Categories

Resources