java java - 6 months ago 17
Javascript 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?

htlm

<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>

Answer

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>