Can someone explain how to appendChild to a parent <div class="...">
and solve this ?
The innerHTML should set the variable str after every <div class='categories'> </div>
it created dynamically when you set a value to the texts and press the button "press"
function addField() {
var categoryValue = document.getElementById("newCateg").value;
var fieldValue = document.getElementById("newField").value;
// var selOption = document.option[selectedIndex.text];
var newCategoryNode = document.getElementsByClassName('categories');
var categoryPart1 = [
' <div class="categories">',
'<input type="checkbox" class="check"/> <a class="titles">'].join('');
var categoryPart2 = [
'</a>',
' <hr/>',
' <input type="checkbox" class="check"/> ' ].join('');
var categoryPart3 = [
' <input type="text" />',
' <br> </br>',
'<hr/>',
'</div>'].join('');
var str=categoryPart1 + categoryValue + categoryPart2 + "" + fieldValue + "" + categoryPart3;
for (var i = 0; i < newCategoryNode.length; i++) {
newCategoryNode[i].innerHTML=str;
}
}
<!DOCTYPE html>
<html>
<body>
<input type="text" id="newCateg" />
<input type="text" id="newField" />
<div class="categories">
<p class="titles">
<input type="checkbox" class="check" onchange="checkAll('divID',true,elem)" />FUN</p>
<hr/>
<div class="field">
<input type="checkbox" class="check" />D
<input type="text" />
</br>
</div>
<input type="checkbox" class="check" />
<label>S</label>
<input type="text" id="c1" />
</br>
<input type="checkbox" class="check" />
<label>A</label>
<input type="text" />
<hr/>
</div>
<input type="button" onclick="addField()" value="Press">
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<input type="text" id="newCateg" />
<input type="text" id="newField" />
<div class="categories">
<p class="titles">
<input type="checkbox" class="check" onchange="checkAll('divID',true,elem)" />FUN</p>
<hr/>
<div class="field">
<input type="checkbox" class="check" />D
<input type="text" />
</br>
</div>
<input type="checkbox" class="check" />
<label>S</label>
<input type="text" id="c1" />
</br>
<input type="checkbox" class="check" />
<label>A</label>
<input type="text" />
<hr/>
</div>
<input type="button" onclick="addField()" value="Press">
</body>
<script>
function addField() {
var categoryValue = document.getElementById("newCateg").value;
var fieldValue = document.getElementById("newField").value;
// var selOption = document.option[selectedIndex.text];
var newCategory = document.getElementsByClassName('categories');
var div = document.createElement('div');
div.setAttribute('class', 'categories');
var a = document.createElement('a');
a.setAttribute('class', 'titles');
var hr = document.createElement('hr');
var input_check = document.createElement('input');
input_check.setAttribute('type', 'checkbox');
input_check.setAttribute('class', 'check');
var input = document.createElement('input');
input.setAttribute('type', 'text');
var br = document.createElement('br');
var textnode = document.createTextNode(fieldValue);
div.appendChild(input);
div.appendChild(a);
div.appendChild(hr);
div.appendChild(input_check);
div.appendChild(textnode);
div.appendChild(input);
div.appendChild(br);
div.appendChild(br);
console.log(div);
var node = document.getElementsByClassName('categories');
for (var i = 0; i < node.length; i++) {
node[i].appendChild(div);
}
}
</script>
</html>
hope this could give you idea on how to do it.
you cannot use appendChild to a node using a string it shoud also be a DOM element
you can check on document.createElement and document.createTextNode function
hope it would help you more on your understanding
According to MDN, Node.appendChild() wants a Node object as its argument. It won't create one from a string of markup, so you'll have to create it yourself.
You can use document.createElement() to create a Node object, then you can set its innerHTML as you like. Once the Node is all set how you want, you can add it to the DOM using appendChild().
If you want to use appendChild() mehtod it doesn't work this way.First you have to create a child using element.createElement() method.Now concentrating on your code i encountered some problem. your getElementsByClassName is returning a nodelist containing all the elements having same class.So if you want to grab it provide it an index.As you have only one it's better to provide [0] index to it.
var newCategoryNode = document.getElementsByClassName('categories')[0];
if you don't provide index in getElementsByClassName() you can also access it
newCategoryNode[0].innerHTMM=str
i removed for loop from you code.If you want to use loop use for...in loop instead as it is a list of object.
var newCategoryNode = document.getElementsByClassName('categories');
for(key in newCategoryNode){
newCategoryNode[key].innerHTML=str;
}
you haven't defined checkAll() function related to one of your input tag.That surely get you an error.I've modified your code and it might give you the result you want
function addField() {
console.log('logged');
var categoryValue = document.getElementById("newCateg").value;
var fieldValue = document.getElementById("newField").value;
// var selOption = document.option[selectedIndex.text];
var newCategoryNode = document.getElementsByClassName('categories')[0];
var categoryPart1 = [
' <div class="categories">',
'<input type="checkbox" class="check"/> <a class="titles">'].join('');
console.log(categoryPart1);
var categoryPart2 = [
'</a>',
' <hr/>',
' <input type="checkbox" class="check"/> ' ].join('');
var categoryPart3 = [
' <input type="text" />',
' <br> </br>',
'<hr/>',
'</div>'].join('');
var str=categoryPart1 + categoryValue + categoryPart2 + fieldValue + "" + categoryPart3;
console.log(str);
newCategoryNode.innerHTML =str;
}
<input type="text" id="newCateg" />
<input type="text" id="newField" />
<div class="categories">
<p class="titles">
<input type="checkbox" class="check" />FUN</p>
<hr/>
<div class="field">
<input type="checkbox" class="check" />D
<input type="text" />
</br>
</div>
<input type="checkbox" class="check" />
<label>S</label>
<input type="text" id="c1" />
</br>
<input type="checkbox" class="check" />
<label>A</label>
<input type="text" />
<hr/>
</div>
<input type="button" onClick="addField();" value="Press">
Related
how to find all duplicate ids when the page is relaod:
Let's say we have html like this:
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />
The idea is to find duplicate ids and add +1 or something like that:
What I want to achieve is:
<input type="radio" id="name1" />
<input type="radio" id="name2" />
<input type="radio" id="name3" />
<input type="radio" id="last1" />
<input type="radio" id="last2" />
JS
$('[id]').each(function(){
var ids = $('[id="'+this.id+'"]');
if(ids.length>1 && ids[0]==this)
$(this).attr('id', $(this).attr('id') + i);
});
Any ideas? Thank you all.
I would strongly recommend you serve valid HTML rather than manipulating Ids.
However, You are were close as attribute value selector may return multiple elements, You need to iterate the matching elements
var handled = [];
$('[id]').each(function() {
if (handled.includes(this.id)) {
return;
}
var elemets = $('[id="' + this.id + '"]');
if (elemets.length > 1) {
handled.push(elemets.attr('id'));
elemets.attr('id', function(index, v) {
return v + (index+1);
});
}
});
//For Readablity
$('[id]').each(function(){
console.log(this.outerHTML)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />
Try like this.
var allId = [];
var data = [];
$('[id]').each(function(){
var ids = $('[id="'+this.id+'"]');
if(allId.indexOf(this.id) < 0){
data[this.id] = 1;
allId.push(this.id);
} else {
data[this.id]++;
}
$(this).attr('id', $(this).attr('id') + data[this.id]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />
No need for jQuery:
const ids = {}
document.querySelectorAll('[id]').forEach(node => {
if (ids[node.id] !== undefined) {
ids[node.id] += 1
} else {
ids[node.id] = 1
}
node.id = `${node.id}${ids[node.id]}`
})
document.querySelectorAll('[id]').forEach(node => console.log(node))
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />
try this
var i = 0;
('[id]').each(function(){
var allIds = $('[id^="'+this.id+'"]').length
var ids = $('[id="'+this.id+'"]');
if(ids.length>1 && ids[0]==this)
var i = allIds - ids.length + 1
$(this).attr('id', $(this).attr('id') + i++);
})
var a = [];
var i =0;
jQuery('[id]').each(function(){
if(a.indexOf(this.id) !== -1){ //checks if id exists in array
i++;
}
else{
i = 1;
a.push(this.id);
}
jQuery(this).attr('id', jQuery(this).attr('id') + i);
});
Explaination : I am storing each new id in array. At each iteration it checks whether the id is repeated, if so then the attribute is incremented to 1.
I have the following form:
<form id="taskform">
Habit: <input id="taskname" type="text">
<textarea id="taskdesc" rows="4" cols="50" name="comment" form="usrform">Description Here...</textarea>
<div>
Good or Bad:
<input type="radio" id="star" name="priority" value="1" checked/><label for="star1" title="Not very important">Good</label>
<input type="radio" id="star" name="priority" value="2"/><label for="star2" title="Kinda important">Bad</label>
</div>
<br>Starting Date: <input id="deadlinedate" type="date">
Times you want to do it: <input type="number" id="reminderdays" min="0">
<span type="button" id="sBtn" value="Add Habit" onclick="newElement()" class="addBtn" >Add Habit</span>
<input type="reset" value="Clear">
</form>
I have a js function which takes the values of each field here and it should add them together:
var li = document.createElement("li");
var inputValue = document.getElementById("taskname").value;
var inputDescription = document.getElementById("taskdesc").value;
var inputStar = document.getElementById("star").value;
var inputDate = document.getElementById("deadlinedate").value;
var inputReminderDays = document.getElementById("reminderdays").value;
var t1 = document.createTextNode(inputValue);
var t2 = document.createTextNode(inputDescription);
var t3 = document.createTextNode(inputStar);
var t4 = document.createTextNode(inputDate);
var t5 = document.createTextNode(inputReminderDays);
now I am trying to combine all of the strings t1,t2,t3,t4 and t5 together and then add to a list object.
it does add to a list if I use just for example t1, by doing this:
li.appendChild(t1);
if I use concat and try to add t2, t3, t4 and t5 to my t1 and then use this
li.appendChild(res);
with res being the sum of all of the values my list is empty and nothing is added,
i am not sure how to do this, I dont know why concat or + doesnt work.
also I can not get the value for my date and radio for some reason.
If all you want to do is to combine the strings then nhy not try this:
var t1 = document.createTextNode(inputValue+' '+inputDescription+' '+inputStar+' '+inputDate+' '+inputReminderDays);
UPDATE:
var output = document.getElementById('output');
function newElement() {
var li = document.createElement("li");
var inputValue = document.getElementById("taskname").value;
var inputDescription = document.getElementById("taskdesc").value;
var inputStar1 = document.getElementById("star1");
var inputStar2 = document.getElementById("star2");
var inputDate = document.getElementById("deadlinedate").value;
var inputReminderDays = document.getElementById("reminderdays").value;
// Since you only have two radio buttons you can use a ternary to get the right value base on if oneis checked or not.
var inputStar = inputStar1.checked ? inputStar1.value : inputStar2.value;
var t1 = document.createTextNode(inputValue + ', ' + inputDescription + ', ' + inputStar + ', ' + inputDate + ', ' + inputReminderDays);
li.appendChild(t1);
output.appendChild(li);
}
<form id="taskform">
Habit: <input id="taskname" type="text"><br/>
<textarea id="taskdesc" rows="4" cols="50" name="comment" form="usrform" placeholder="Description Here..."></textarea>
<div>
Good or Bad:
<input type="radio" id="star1" name="priority" value="1" checked/><label for="star1" title="Not very important">Good</label>
<input type="radio" id="star2" name="priority" value="2" /><label for="star2" title="Kinda important">Bad</label>
</div>
<br>Starting Date: <input id="deadlinedate" type="date"> Times you want to do it: <input type="number" id="reminderdays" min="0" value="1">
<button type="button" id="sBtn" value="Add Habit" onclick="newElement()" class="addBtn">Add Habit</button>
<input type="reset" value="Clear">
</form>
<hr/>
<ul id="output">
</ul>
I'm trying to change a redirect link using check boxes that append to the URL and a button that uses the changed URL. Im still a beginner to JavaScript and am a little lost as to where i'm going wrong.
My code:
<html>
<form>
<div class="element1">"
<input type="checkbox" name="name1" id="id1" value="val1" class="hidden" ></label></div>
<div class="element2">"
<input type="checkbox" name="name2" id="id2" value="val2" class="hidden" ></label></div>
<div class="element3">"
<input type="checkbox" name="name3" id="id3" value="val3" class="hidden" ></div>
<div class="element00">
<input type="button"onclick="myFunction(calculatedUrl());" name="button1" id="itemA" value="valA" ></label></div>
</form>
<script>
function calculatedUrl(){
var totalString=""
var link1="some text"
var link2="more text"
var link3="something else"
if(document.getElementById("id1").checked == true){
var totalString = totalString.concat(link1);
}
if(document.getElementById("id2").checked == true){
var totalString = totalString.concat(link2);
}
if(document.getElementById("id3").checked == true){
var totalString = totalString.concat(link3);
}
return totalString
}
function myFunction(id){
var original="http://myoriginalurl"
var addition=id
var new=original.concat(addition)
//for testing
window.alert(new)
document.getElementById("test1").innerHTML= new;
//for the real redirecting not active for now
//window.location=new
}
</script>
</html>
<html>
<form>
<div class="element1">"
<input type="checkbox" name="name1" id="id1" value="val1" class="hidden" ></label></div>
<div class="element2">"
<input type="checkbox" name="name2" id="id2" value="val2" class="hidden" ></label></div>
<div class="element3">"
<input type="checkbox" name="name3" id="id3" value="val3" class="hidden" ></div>
<div class="element00">
<input type="button"onclick="myFunction(calculatedUrl());" name="button1" id="itemA" value="valA" ></label></div>
</form>
<script>
function calculatedUrl(){
var totalString=""
var link1="some text"
var link2="more text"
var link3="something else"
if(document.getElementById("id1").checked == true){
var totalString = totalString.concat(link1);
}
if(document.getElementById("id2").checked == true){
var totalString = totalString.concat(link2);
}
if(document.getElementById("id3").checked == true){
var totalString = totalString.concat(link3);
}
return totalString
}
function myFunction(id){
var original="http://myoriginalurl"
var addition=id
console.log(id);
var n =original.concat(addition)
//for testing
window.alert(n)
document.getElementById("test1").innerHTML= n;
//for the real redirecting not active for now
//window.location=new
}
</script>
</html>
Currently in your code change the below, new to newurl - new is a reserved word.
function myFunction(id){
var original="http://myoriginalurl"
var addition=id
var newurl =original.concat(addition)
//for testing
window.alert(newurl)
document.getElementById("test1").innerHTML= newurl;
//for the real redirecting not active for now
//window.location=new
}
I dont see a tag with id=test1, so you will get null exception in the console browser. Add a tag based on that and test.
I have added a snippet, please check.
<html>
<form>
<div class="element1">"
<input type="checkbox" name="name1" id="id1" value="val1" class="hidden" ></label></div>
<div class="element2">"
<input type="checkbox" name="name2" id="id2" value="val2" class="hidden" ></label></div>
<div class="element3">"
<input type="checkbox" name="name3" id="id3" value="val3" class="hidden" ></div>
<div class="element00">
<input type="button"onclick="myFunction(calculatedUrl());" name="button1" id="itemA" value="valA" ></label></div>
</form>
<script>
function calculatedUrl(){
var totalString=""
var link1="some text"
var link2="more text"
var link3="something else"
if(document.getElementById("id1").checked == true){
var totalString = totalString.concat(link1);
}
if(document.getElementById("id2").checked == true){
var totalString = totalString.concat(link2);
}
if(document.getElementById("id3").checked == true){
var totalString = totalString.concat(link3);
}
return totalString
}
function myFunction(id){
var original="http://myoriginalurl"
var addition=id
console.log(id);
var n =original.concat(addition)
//for testing
window.alert(n)
document.getElementById("test1").innerHTML= n;
//for the real redirecting not active for now
//window.location=new
}
</script>
</html>
Can you help me for changing value with javascript, but code no have id or class here is code:
<label for="flights-origin-prepop-whitelabel_en">Origin</label>
I want change "Origin" with different word.
Some examples of my code:
<button role="flights_submit" type="submit">Search</button>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text"
name="destination_name"
autocomplete="off" required=""
id="flights-destination-prepop-whitelabel_en"
placeholder="Destination"
data-label="Destination"
role="flights-destination"
data-modal-modifier="whitelabel_en"
data-placeholder-initialized="true">
<input type="hidden"
name="destination_iata"
id="flights-destination-whitelabel_en" value="">
</div>
How can change this placeholder "Destination", and label text Destination?
Thanks
You can change the origin texto doing this:
document.querySelector("label[for='flights-origin-prepop-whitelabel_en']").textContent = 'New Text';
Yes, sure, you can use querySelector with label selector including for data
console.log(document.querySelector("label[for='flights-destination-prepop-whitelabel_en']"))
<button role="flights_submit" type="submit">Search</button>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text"
name="destination_name"
autocomplete="off" required=""
id="flights-destination-prepop-whitelabel_en"
placeholder="Destination"
data-label="Destination"
role="flights-destination"
data-modal-modifier="whitelabel_en"
data-placeholder-initialized="true">
<input type="hidden"
name="destination_iata"
id="flights-destination-whitelabel_en" value="">
</div>
You can find the correct element using an "attribute selector" that looks for the for attribute and a specific value for it.
var btn = document.querySelector("button");
btn.addEventListener("click", function(){
var el = document.querySelector("[for=flights-destination-prepop-whitelabel_en]");
el.textContent = "New Value";
var input = document.getElementById("flights-destination-prepop-whitelabel_en");
input.setAttribute("placeholder","New Value");
});
<button role="flights_submit" type="button">Search</button>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text"
name="destination_name"
autocomplete="off" required=""
id="flights-destination-prepop-whitelabel_en"
placeholder="Destination"
data-label="Destination"
role="flights-destination"
data-modal-modifier="whitelabel_en"
data-placeholder-initialized="true">
<input type="hidden"
name="destination_iata"
id="flights-destination-whitelabel_en" value="">
</div>
The first step would be to set an array of the elements you want to target, which in this case is label. Then you would iterate through that array using a for loop to see if the textContent of that label is what you wanted to change. Finally, once you've 'hooked' the label you need, you can change the attributes for it as necessary. Please also note that textContent method is not cross browser compliant and so I've included a ternary script that will circumvent that thanks to this handy StackOverflow post .
HTML:
<button role="flights_submit" type="submit">Search</button>
<br/>
<br/>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text" name="destination_name" autocomplete="off" required="" id="flights-destination-prepop-whitelabel_en" placeholder="Destination" data-label="Destination" role="flights-destination" data-modal-modifier="whitelabel_en" data-placeholder-initialized="true">
<br/>
<br/>
<label for="somethingElse">OtherLabel</label>
<input type="text" id='somethingElse'>
<input type="hidden" name="destination_iata" id="somethingElse" value="">
</div>
JavaScript:
//https://stackoverflow.com/a/285608/5076162
//https://stackoverflow.com/a/13506703/5076162
var labelArray = document.getElementsByTagName('LABEL');
console.log(labelArray);
var textToChange = 'Destination';
for (var i = 0; i < labelArray.length; i++) {
var currentLabel = labelArray[i]
var text = ('innerText' in labelArray[i]) ? 'innerText' : 'textContent';
if (currentLabel[text] === 'Destination') {
var matchingInput = document.getElementById(currentLabel.htmlFor);
var newText = 'changedDestination';
var newPlaceHolder = 'changedPlaceHolder';
currentLabel[text] = newText;
matchingInput.placeholder = newPlaceHolder;
}
}
jsfiddle Example
//https://stackoverflow.com/a/285608/5076162
//https://stackoverflow.com/a/13506703/5076162
var labelArray = document.getElementsByTagName('LABEL');
console.log(labelArray);
var textToChange = 'Destination';
for (var i = 0; i < labelArray.length; i++) {
var currentLabel = labelArray[i]
var text = ('innerText' in labelArray[i]) ? 'innerText' : 'textContent';
if (currentLabel[text] === 'Destination') {
var matchingInput = document.getElementById(currentLabel.htmlFor);
var newText = 'changedDestination';
var newPlaceHolder = 'changedPlaceHolder';
currentLabel[text] = newText;
matchingInput.placeholder = newPlaceHolder;
}
}
<button role="flights_submit" type="submit">Search</button>
<br/>
<br/>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text" name="destination_name" autocomplete="off" required="" id="flights-destination-prepop-whitelabel_en" placeholder="Destination" data-label="Destination" role="flights-destination" data-modal-modifier="whitelabel_en" data-placeholder-initialized="true">
<br/>
<br/>
<label for="somethingElse">OtherLabel</label>
<input type="text" id='somethingElse'>
<input type="hidden" name="destination_iata" id="somethingElse" value="">
</div>
I'm trying to view the value selected in a radio button. The form is:
<form onsubmit="return false;">
<fieldset>
<h3>Textos</h3>
<label>Nombre:</label>
<input type="text" name="nombre"/>
<label>Apellido:</label>
<input type="text" name="apellido" />
<label>ContraseƱa:</label>
<input type="password" name="contrasena" />
<div class="limpia"></div>
</fieldset>
<fieldset>
<h3>Gustos musicales:</h3>
<label>POP <input type="checkbox" name="pop" value="POP" class="gmusicales"
/></label>
<label>ROCK <input type="checkbox" name="rock" value="ROCK" class="gmusicales"
/></label>
<label>HIP-HOP <input type="checkbox" name="hiphop" value="HIP-HOP"
class="gmusicales"
/></label>
<label>METAL <input type="checkbox" name="metal" value="METAL" class="gmusicales"
/></label>
<div class="limpia"></div>
</fieldset>
<fieldset>
<h3>Sistema operativo</h3>
<label>Windows <input type="radio" name="SO" value="Windows" class="soperativo"/>
</label>
<label>Linux <input type="radio" name="SO" value="Linux" class="soperativo"/>
</label>
<label>Mac <input type="radio" name="SO" value="Mac" class="soperativo"/></label>
<div class="limpia"></div>
</fieldset>
<fieldset>
<input type="reset" value="Borrar"/>
<input type="submit" onclick=muestra() value="Probar" />
<div class="limpia"></div>
</fieldset>
</form>
The problem is in my JavaScript code:
var nom;
var ape;
var con;
var gustos = document.getElementsByClassName("gmusicales");
var sistema = document.getElementById("soperativo");
var resultado;
var i;
var h2 = document.createElement("h2");
function muestra()
{
nom = document.forms[0].elements.nombre.value;
ape = document.forms[0].apellido.value;
con = document.forms[0].contrasena.value;
resultado = nom + " " + ape + " " + con;
for(i=0; i<=gustos.length; i++)
{
if (gustos[i].checked)
{
resultado = resultado + " " + gustos[i].value;
alert(resultado);
}
}
for(i=0; i<=sistema.length; i++)
{
if (sistema[i].checked)
{
resultado = resultado + " " + sistema[i].value;
alert(resultado);
}
}
document.body.appendChild(h2);
document.h2.appenChild(resultado);
}
What I want is to view the values of sistema operativo fieldset. You can choose only one. When I select it, I don't view anything. When I select the other one, that is a checkbox, I can view the values.
I want to create an h2 html tag and to print the values.
How can I do it?
At first you write:
var sistema = document.getElementById("soperativo");
That would give you a single element (uno solo), if there was any.
But in your code, I can see that you have elements with the class soperativo, not an id soperativo.
Use this instead of the line above:
var sistema = document.getElementsByClassName("soperativo");
I know that it's a pure Javascript question.. but how you didn't specified in the question that you want the solution in pure Javascript, here is my solution in jQuery:
$(document).ready(function(){
$('input[type=submit]').click(function(){
$('#resultado').val($('.soperativo:checked').val());
return false;
});
});
http://jsfiddle.net/h9GJa/
More more easy, don't you think?