View selected values of a form - javascript

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?

Related

trying to add some Js strings together

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>

How to make one of three inputs type button requierd required

My problem is that I have one form with some fields and three inputs type button, they all represents one message. I want to make chooseing one of three messages required. My code is bellow:
<input id="poruka1" type="button" class="hm_datumibtn poruka" name="poruka1" value="Pored mene, sve želje " >
<input id="poruka2" type="button" class="hm_datumibtn poruka" name="poruka2" value="Pored sebe, sve želje " >
<input id="poruka3" type="button" class="hm_datumibtn poruka" name="poruka3" value="Pored tebe, sve želje " >
Do you have any idea how can I solve this kind of problem?
<script>
function upis(){
//var datum = $(this).find('.datum').val();
//var poruka = $(this).find('.poruka').val();
//var poruka = $(this).attr('value');
if (poruka_forma.poruka1.value == '' && poruka_forma.poruka2.value == ''&& poruka_forma.poruka3.value == '') {
alert('You have to choose message.');
return false;
}
else {
myForm.submit();
}
var ime = document.getElementById("ime").value;
var ime_slavljenik = document.getElementById("ime_slavljenik").value;
var elementsdate = document.getElementsByClassName("selected_date");
var datum = elementsdate[0].value;
var elements = document.getElementsByClassName("selected");
var poruka = elements[0].value;
//var poruka = document.getElementById("poruka").value;
//var datum = document.getElementById("datum").value;
//var poruka = document.getElementById("poruka").value;
//var email = document.getElementById("email").value;
//var dataString = "ime="+encodeURIComponent(ime)+"&ime_slavljenik="+encodeURIComponent(ime_slavljenik);
$.ajax({
type:"post",
url: "upis.php",
cashe: false,
//data: dataString+'&datum='+datum+'&poruka='+poruka,
data: {ime:ime,ime_slavljenik:ime_slavljenik,datum:datum, poruka:poruka},
success: function(data){
//window.alert(data);
document.getElementById("placefortableanketa").innerHTML = data;
},
error: function (req, status, err) {
console.log('Something went wrong', status, err);
}
})
return false;
}
</script>
I think you might want to use <input type="radio" /> instead. Example:
<form>
<input type="radio" id="radio_btn_1" name="radio_btn" value="choice_1" required="required" checked="checked" /><label for="radio_btn_1">Choice 1</label><br />
<input type="radio" id="radio_btn_2" name="radio_btn" value="choice_2" required="required" /><label for="radio_btn_2">Choice 2</label><br />
<input type="radio" id="radio_btn_3" name="radio_btn" value="choice_3" required="required" /><label for="radio_btn_3">Choice 3</label><br />
</form>
You can add required attributes to make them required. Also, adding checked attributes will make a radio button selected by default.
You can also use <label> with for attribute. When that label is clicked, it selects a radio button that it refers to by id in its for attribute.
Edit: I saw your comment that you don't want to use radio buttons because of the design. You can actually hide the radio buttons, and just use <label> with for attributes. Example:
<style>
#radio_btn_1:checked + label{background-color:red;}
#radio_btn_2:checked + label{background-color:red;}
#radio_btn_3:checked + label{background-color:red;}
</style>
<form>
<input style="display:none;" type="radio" id="radio_btn_1" name="radio_btn" value="choice_1" required="required" checked="checked" /><label for="radio_btn_1">Choice 1</label><br />
<input style="display:none;" type="radio" id="radio_btn_2" name="radio_btn" value="choice_2" required="required" /><label for="radio_btn_2">Choice 2</label><br />
<input style="display:none;" type="radio" id="radio_btn_3" name="radio_btn" value="choice_3" required="required" /><label for="radio_btn_3">Choice 3</label><br />
</form>

Add radio button input to textbox input and store it in a list?

I have a textbox where users can enter their name and 2 radio buttons, one for Mr. and one for Mrs. .
When the user hits the submit button I want a function to run that checks which radio button the user checked and add it to their name, then store it in a list.
For example lets say they enter their name as John and click the Mr. box. I want it to add Mr. to john and then store it in a list. So it would store Mr.John is a list.
Im at a loss as to how to do this, Heres what I've got so far:
var UserNames = []
var NameAdd = function() {
var name = document.getElementById("nametextbox").value;
UserNames.push("name");
}
If that code is correct it should take the input from the textbox and store it in a list.
Heres the css for the radio buttons:
#CheckBox1,#CheckBox2 {
float:left;
margin: 600px 20px 20px 60px;
color: #b2aba4;
}
And heres the html:
<div id="CheckBox1"><input type="radio" Name="Mr."/>Mr.</div>
<div id="CheckBox2"><input type="radio" Name="Mrs."/>Mrs.</div>
Any help is appreciated im at a loss here. Ik that it should be a if/else statement but past that im clueless.
I would change your markup to this:
<div id="CheckBox1"><input type="radio" name="salutation" value="Mr." />Mr.</div>
<div id="CheckBox2"><input type="radio" name="salutation" value="Mrs." />Mrs.</div>
and you can then get the value with this JavaScript:
var salutation = document.querySelector('input[name = "salutation"]:checked').value;
If you want it at Client side this may help you:
WORKING:DEMO
JS
$("button").click(function()
{
var curSex = $("input[type=radio]").val();
var curName = $("input[type=text]").val();
document.getElementById("print").innerHTML = "Hello" + " " + curSex + curName;
});
HTML
<div id="CheckBox1"><input type="radio" Name="Mr." value="Mr." />Mr.</div>
<div id="CheckBox2"><input type="radio" Name="Mrs." value="Mrs." />Mrs.</div>
Enter Name : <input type="text" name="name" />
<button>Submit</button>
<p id="print"></p>
<form name="send" method="POST">
<input type="text" name="name" id ="userName" />
<div id="CheckBox1"><input type="radio" id ="mr" value="Mr." Name="title"/>Mr.</div>
<div id="CheckBox2"><input type="radio" id ="mrs" value="Mrs." Name="title"/>Mrs.</div>
<input type="button" name="button" value="Submit" onClick="getInfo(this.form);" />
</form>
<p id="info"></p>
java script code
function getInfo(form) {
var userName = document.getElementById("userName");
var mr = document.getElementById('mr');
var mrs = document.getElementById('mrs');
var data = [];
if (userName.value !== "") {
if (mr.checked) {
data.title = mr.value;
mrs.checked = false;
} else if (mrs.checked) {
data.title = mrs.value;
mr.checked = false;
}
data.name = userName.value;
document.getElementById("info").innerHTML = "Hello:" + data.title + " " + data.name;
}
//console.log(data);
}
demo

getElementsByClassName and innerHTML

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

Replace text in form using javascript

I have a form that has several fields. The first field is called subject. What I want to do is disable the ability for the user to type in the field, but it still show, and the text they enter into three other fields show up with spaces between the variables in the first field. Example: In this scenario: "Second_Field: John" "Third_Field: Doe" "Forth_Field: New part" then on first field, subject, it will show: John Doe New Part
Thanks for any help.
You can try the following:
<!-- HTML -->
<input type="text" id="subject" disabled="disabled">
<input type="text" id="field1">
<input type="text" id="field2">
<input type="text" id="field3">
// JavaScript
var fields = [];
for (var i = 1; i <= 3; i++) {
fields.push(document.getElementById("field" + i).value);
}
document.getElementById("subject").value = fields.join(" ");
Try this:
<script>
function UpdateText()
{
document.getElementById("subject").value =document.getElementById("Field1").value + " " + document.getElementById("Field2").value + " " + document.getElementById("Field3").value;
}
</script>
<input type="text" id="subject" disabled="disabled"/>
<input type="text" id="Field1" onchange="UpdateText()";/>
<input type="text" id="Field2" onchange="UpdateText()";/>
<input type="text" id="Field3" onchange="UpdateText()";/>
HTML:
<form>
<p><input id="subject" name="subject" disabled size="60"></p>
<p><input id="Second_Field" class="part">
<input id="Third_Field" class="part">
<input id="Fourth_Field" class="part"></p>
</form>
​
JavaScript:
var updateSubject = function() {
var outArray = [];
for (var i=0;i<parts.length;i++) {
if (parts[i].value !== '' ) {
outArray.push(parts[i].value);
}
}
document.getElementById('subject').value = outArray.join(' ');
};
var parts = document.getElementsByClassName('part');
for (var i=0;i<parts.length;i++) {
parts[i].onkeydown = updateSubject;
}
​

Categories

Resources