DOM javascript Form Gender Radio button "on" value output - javascript

function myfunction() {
var x = document.getElementById("myform").elements;
var para = x[0].value;
for (var i = 0; i < x.length; i++) {
para = para.concate(x[i].value);
}
document.getElementById("demo").innerHTML = para;
}
<form id="myform">
name<input type="textbox" name="fname"> email
<input type="textbox" name="email"> number
<input type="textbox" name="number"> Gender
<input type="radio" name="gender" checked>Male
<input type="radio" name="gender">Female
<button type="button" onclick="myfunction()"> Click me</button>
</form>
<p id="demo"></p>
I tried but i think there is a bug. I want to display whole line that the user enter but clicking it is not working. At mid, it was working but after not working. I want output as jaykumar jay#123 111111 Male . And also how to get Gender Male/Female in demo. Instead it is giving me only "on" .How to get value Male or Female in demo.

Because you didn't add value to radio input. According to Mozilla doc:
If you omit the value attribute in the HTML, the submitted form data assigns the value on to the group.
function myfunction() {
var x = document.getElementById("myform").elements;
var para = x[0].value;
for (var i = 0; i < x.length; i++) {
para = para.concat(x[i].value);
}
document.getElementById("demo").innerHTML = para;
}
<form id="myform">
name<input type="textbox" name="fname"> email
<input type="textbox" name="email"> number
<input type="textbox" name="number"> Gender
<input type="radio" checked id="male" name="gender" value="Male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="Female">
<label for="female">Female</label>
<button type="button" onclick="myfunction()"> Click me</button>
</form>
<p id="demo"></p>

you need to have a different treatment when it's a radio, in addition of adding the value for each radio
function myfunction() {
var x = document.getElementById("myform").elements;
var para = x[0].value;
for (var i = 0; i < x.length; i++) {
if ((x[i].type === 'radio' && x[i].checked) || x[i].type === 'text') {
para = para.concate(x[i].value);
}
}
document.getElementById("demo").innerHTML = para;
}
<form id="myform">
name<input type="text" name="fname"> email
<input type="text" name="email"> number
<input type="text" name="number"> Gender
<input type="radio" value="Male" name="gender" checked>Male
<input type="radio" value="Female" name="gender">Female
<button type="button" onclick="myfunction()"> Click me</button>
</form>
<p id="demo"></p>

Related

Javascript calculation resulting NaN

I have a form to calculate the total value from a form but it results in a nan error even though the values of the html inputs is numerical. What am I doing wrong?
function myFunction() {
var y = document.getElementsByName("optradio").value;
var z = document.getElementsByName("extra-hours").value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
<label class="radio-inline">
<input type="radio" name="optradio" value="25">Half day (3hrs)
</label>
<label class="radio-inline">
<input type="radio" name="optradio" value="50">Full day (6hrs)
</label>
<input type="number" value="" min="0" max="6" class="form-control" name="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
You must cycle through the radios to get the value. getElementsByName returns multiple elements.
<label class="radio-inline">
<input type="radio" name="optradio" value="25">Half day (3hrs)
</label>
<label class="radio-inline">
<input type="radio" name="optradio" value="50">Full day (6hrs)</label>
<input type="number" value="" min="0" max="6" class="form-control" name="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
<script>
function valueOfRadio(name) {
// Get all of the radios by name
var radios = document.getElementsByName(name);
// Go through each one
for (var i = 0, length = radios.length; i < length; i++) {
// If it's checked, lets return it's value
if (radios[i].checked) {
return radios[i].value;
}
}
}
function myFunction() {
// Go get the right radio value
var y = valueOfRadio('optradio');
// Same problem here. Multiple returned, but we know we only have one element so we index to 0.
//You could alternatively use getElementsById for this which will return a single node.
var z = document.getElementsByName("extra-hours")[0].value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
</script>
getElementsByName returns an array and you have to test all the radios to see if they are checked.
Try it:
<label class="radio-inline">
<input type="radio" name="optradio" value="25">Half day (3hrs)
</label><label class="radio-inline"><input type="radio" name="optradio" value="50">Full day (6hrs)</label>
<input type="number" value="" min="0" max="6" class="form-control" id="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
<script>
function myFunction() {
var radios = document.getElementsByName("optradio");
var y = 0;
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
y += +radios[i].value;
}
}
var z = document.getElementById("extra-hours").value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
</script>
Actually getElementsByName returns array of elements with the name given, name optradio is allocated for 2 radio buttons, so you need to do like this
function myFunction() {
var radioarray = document.getElementsByName("optradio");
var y;
for (var i = 0; i < radioarray.length; i++) {
if (radioarray[i].checked) {
y = radioarray[i].value;
}
}
var z = document.getElementsByName("extra-hours")[0].value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
<label class="radio-inline">
<input type="radio" name="optradio" value="25">Half day (3hrs)
</label>
<label class="radio-inline">
<input type="radio" name="optradio" value="50">Full day (6hrs)
</label>
<input type="number" value="" min="0" max="6" class="form-control" name="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
Here is an example using a select instead of radio buttons, and it looks a little more compact and clean. I also used jQUery instead of plain Javascript because the code is a lot cleaner.
function myFunction() {
var result = parseInt($("[name=optradio]").val()) + parseInt($("[name=extra-hours]").val());
$("#result").text(result);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="optradio">
<option value="25">Half day (3hrs)
<option value="50">Full day (6hrs)
</select>
<input type="number" value="0" min="0" max="6" class="form-control" name="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
document.getElementsByName("...")
returns a node list, not an individual node. You should use an id to select just a single node (preferred). That is
var y = document.getElementById("optradio").value
var z = document.getElementById("extra-hours").value
The properties "name" and "id" have different meanings, so make sure you use the one you actually mean.
If you want a unique identifier, use "id", if you want to group a selection of your DOM elements, use "name".
Additionally, the value for the radio button is always the same, you need to apply it conditionally based on the 'selected' property.
function myFunction() {
var half = document.getElementById("half");
var full = document.getElementById("full");
var y = half.checked ? half.value : full.value;
var z = document.getElementById("extra-hours").value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
<label class="radio-inline">
<input type="radio" name="optradio" id="half" value="25" checked>Half day (3hrs)
<input type="radio" name="optradio" id="full" value="50">Full day (6hrs)
</label>
<input type="number" value="" min="0" max="6" class="form-control" id="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
Finally, although I'm not going to show it, you're probably best learning jQuery now; everything else uses jQuery. Everyone uses jQuery because it's better than base javascript. As Christian Juth showed in his answer, you probably want to make it a selection box, too.

merge textbox values with javascript by element type

I have 3 textboxs.Their names and ids are different.I can merge their values with their names or ids but I need to merge their values with type. How can I do it.
<input type="text" id="txt1" name="textbox1">
<input type="text" id="txt2" name="textbox2">
<input type="text" id="txt3" name="textbox3">
You can get all the textbox elements by their type using document.querySelectorAll("input[type=text]").
If by merge you mean concatenating the values.
var textBoxes= document.querySelectorAll("input[type=text]");
var mergedValue;
for(var i=0;i<textBoxes.length;i++)
{
mergedValue+=textBoxes[i].value;
}
var dataVal=document.querySelectorAll('[type=text]');
var myVal="";
dataVal.forEach(function(entry) {
myVal+=entry.value;
});
console.log(myVal);
<input type="text" id="txt1" name="textbox1" value="2">
<input type="text" id="txt2" name="textbox2" value="2">
<input type="text" id="txt3" name="textbox3" value="2">
Here is another possible solution.
function mergeData() {
var textboxes = document.getElementsByTagName("input");
var mergedText = "";
for (var i = 0; i < textboxes.length; i++) {
if (textboxes[i].type === "text" ) {
mergedText = mergedText + textboxes[i].value;
}
}
document.getElementById("merged").innerHTML = mergedText;
}
<input type="text" id="txt1" name="textbox1">
<input type="text" id="txt2" name="textbox2">
<input type="text" id="txt3" name="textbox3">
<button onclick="mergeData()">Merge</button>
<div id="merged"></div>

Read data from form, and creating object using it

I have a problem with reading data from my HTML form, and then creating an object using that data. I am making a simple front end portfolio website, and in "Contact" part I would like to manage users to contact me using this form. Here is the code, so if you have any suggestion, please let me know.
This is how I created HTML form and JS:
var users = [];
var createUser = function(){
var form = document.myForm;
//getting data
if(form.name.value == ""){
alert("Please, enter your name.");
}else{
var name = form.name.value;
}
if(form.surname.value == ""){
alert("Please, enter your surname.");
}else{
var surname = form.surname.value;
}
if(form.email.value == ""){
alert("Please, enter your email.");
}else{
var email = form.email.value;
}
if(form.phone.value == ""){
alert("Please, enter your phone number.");
}else{
var phone = form.phone.value;
}
var radSex = form.radSex;
var sex;
for(var i=0; i<radSex.length; i++){
if(radSex[i].checked){
sex = radSex[i].value;
}
}
var radAge = form.radAge;
var age;
for(var i=0; i<radAge.length; i++){
if(radAge[i].checked){
age = radAge[i].value;
}
}
var message = form.getElementByClassName("message").value;
//creating user
var user = {
firstName: name,
lastName: surname,
email: email,
phoneNumber: phone,
sex: sex,
age: age,
message: message
};
//putting into array
users.push(user);
};
function check(){
alert(users[0]);
};
//listening for event
var submitBtn = document.getElementById("submitButton");
submitBtn.addEventListener("click", createUser);
submitBtn.addEventListener("click", check);
<form action="submit" name="myForm">
<p>
<input type="text" name="name" value="Name" class="textbox">
</p>
<p>
<input type="text" name="surname" value="Surname" class="textbox">
</p>
<p>
<input type="text" name="email" value="Email Address" class="textbox">
</p>
<p>
<input type="text" name="phone" value="Phone Number" class="textbox">
</p>
<p>Sex:</p>
<p>
<label>Male </label>
<input type="radio" name="radSex" value="male" checked="checked">
<label> Female </label>
<input type="radio" name="radSex" value="female">
</p>
<p>Age:</p>
<p>
<label><25 </label>
<input type="radio" name="radAge" value="<25" checked="checked">
<label> 25<50 </label>
<input type="radio" name="radAge" value="25<50">
<label> 50<100</label>
<input type="radio" name="radAge" value="50<100">
</p>
<p>
<textarea class="message">Message</textarea>
</p>
<button type="button" class="btn btn-primary btn-block" id="submitButton">Send</button>
</form>
IMO, you should use serialize()
$("form").serialize();
You can select one or more form elements.
Let say, you've large form with lots of fields in it, you can just use the serialize to collect (inputs with name only) all the field values by a single line.
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
let submitButton = document.querySelector("#submitButton");
submitButton.addEventListener("click",function(){
let nameValue = document.querySelector("[name=name]").value;
let surnameValue = document.querySelector("[name=surname]").value;
let emailValue = document.querySelector("[name=email]").value;
let phoneValue = document.querySelector("[name=phone]").value;
let sexValue = document.querySelector("[name=radSex]").value;
let ageValue = document.querySelector("[name=radAge]").value;
let messageValue = document.querySelector(".message").value;
let backObject = {
"name": nameValue,
"surname": surnameValue,
"email": emailValue,
"phone": phoneValue,
"sex": sexValue,
"age": ageValue,
"message": messageValue
};
console.log(backObject);
});
<form action="submit" name="myForm">
<p>
<input type="text" name="name" value="Name" class="textbox">
</p>
<p>
<input type="text" name="surname" value="Surname" class="textbox">
</p>
<p>
<input type="text" name="email" value="Email Address" class="textbox">
</p>
<p>
<input type="text" name="phone" value="Phone Number" class="textbox">
</p>
<p>Sex:</p>
<p>
<label>Male </label>
<input type="radio" name="radSex" value="male" checked="checked">
<label> Female </label>
<input type="radio" name="radSex" value="female">
</p>
<p>Age:</p>
<p>
<label><25 </label>
<input type="radio" name="radAge" value="<25" checked="checked">
<label> 25<50 </label>
<input type="radio" name="radAge" value="25<50">
<label> 50<100</label>
<input type="radio" name="radAge" value="50<100">
</p>
<p>
<textarea class="message">Message</textarea>
</p>
<button type="button" class="btn btn-primary btn-block" id="submitButton">Send</button>
</form>

how to output value from radio button

i am trying to output value of radio with innerHTML
But i do not succeed in this. What is going wrong?
<script>function changeText(){
var userInputgender = document.getElementByName('gender');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
document.getElementById('output1').innerHTML = userInputgender;
break;
}
}
return false;
}
</script>
<form method="get" onsubmit="return changeText()">
<input type="radio" name="gender" id="male" value="man" />Man
<input type="radio" name="gender" id="female" value="woman" />Woman<br />
<br /><br />
<input type="submit" value="Submit" />
</form>
<!-- here comes the output -->
<b id='output1'></b><br />
It's getElementsByName (plural).
function changeText() {
var userInputgender = document.getElementsByName('gender');
for (var i = 0, length = userInputgender.length; i < length; i++) {
if (userInputgender[i].checked) {
document.getElementById('output1').innerHTML = userInputgender[i].value;
break;
}
}
return false;
}
jsFiddle example
And you probably want the value (userInputgender[i].value;) returned to your div.
You could use jquery, it's much better. Look at this example:
HTML:
<input type="radio" name="gender" id="male" value="man" />Man
<input type="radio" name="gender" id="female" value="woman" />Woman<br />
<input id="button" type="button" value="Submit" />
<b id='output1'></b>
JS:
$("#button").click(function(){
var $name = $('input[name=gender]:checked').val();
$("#output1").text($name);
});
http://jsfiddle.net/LZWau/1/
<script type="text/javascript">
function changeText()
{
//get your 2 radio buttons
var userInputgender = document.getElementsByName('gender');
//loop on the buttons you found
for(var i=0;i<userInputgender.length;i++)
{
//is the button checked?
if(userInputgender[i].checked)
{
//fill the result element with the button value
document.getElementById('output1').innerHTML = userInputgender[i].value;
}
}
//return false so the form won't commit
return false;
}
</script>
<form method="get" onsubmit="return changeText()">
<input type="radio" name="gender" id="male" value="man" />Man
<input type="radio" name="gender" id="female" value="woman" />Woman<br />
<br /><br />
<input type="submit" value="Submit" />
</form>
<b id='output1'></b><br />
</script>
http://jsfiddle.net/ayy28/4/
var form = document.forms[0];
var userInputsgender = document.getElementsByName('gender');
form.addEventListener('submit', function(evt){
evt.preventDefault();
for (var i = 0, length = userInputsgender.length; i < length; i++) {
if (userInputsgender[i].checked) {
document.getElementById('output1').innerHTML = userInputsgender[i].value;
break;
}
else {
document.getElementById('output1').innerHTML = 'No gender was selected!';
}
}
});

View selected values of a form

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?

Categories

Resources