Radio Button selected value; choice of 3 options - javascript

Using HTML and JavaScript only, I am trying to get the first name, surname details and then a choice of favourite colour from three radio buttons. I can get the first name and surname to work, but cannot do the radio buttons?
HTML file:
<html>
<title>Task 3</title>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form name="formDetails">
First Name:<input type="text" id="firstName"><br>
Last Name:<input type="text" id="lastName"><br>
<p>Favourite Colour:</p>
<input type="radio" name="colour" value="Red">Red<br>
<input type="radio" name="colour" value="Blue">Blue<br>
<input type="radio" name="colour" value="Green">Green<br>
<input type="button" onclick="display()" value="Submit">
</form>
</body>
JavaScript file:
function display(){
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
alert(firstName + " " + lastName);
}
I have no idea how to implement the radio buttons? I have seen some people using jQuery, but I want to stick to just JavaScript here as I am fairly new.
Thanks.

Js:
var colour=document.querySelector('input[name="colour"]:checked').value;
alert(colour);

Steps:
Add a class to all your input tags named check_in.
Use javascript to find all tags with this class
Iterate through each tag to determine which of them is checked. If a tag is checked add it to the variable named results.
Finally get First name and Last name from input box and add these values to your variable named results
function display() {
results = {}
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var all_input = document.getElementsByClassName('check_in');
for (var i = 0; i < all_input.length; ++i) {
if (all_input[i].checked == true) {
results['option'] = all_input[i].value;
}
}
results['firstname'] = firstName;
results['lastname'] = lastName;
console.log(results);
alert('firstname:' + results['firstname'] + ' lastname: ' + results['lastname'] + ' option: ' + results['option']);
}
margin:50px auto auto;
<html>
<title>Task 3</title>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form name="formDetails">
First Name:
<input type="text" id="firstName">
<br>Last Name:
<input type="text" id="lastName">
<br>
<p>Favourite Colour:</p>
<input type="radio" name="colour" value="Red" class="check_in">Red
<br>
<input type="radio" name="colour" value="Blue" class="check_in">Blue
<br>
<input type="radio" name="colour" value="Green" class="check_in">Green
<br>
<input type="button" onclick="display()" value="Submit">
</form>
</body>

Related

Radio Button failed sometimes to get value

$("#btn").on("click",()=>{
const rdValue = $("#frm").serialize();
var _IsOccupant = false;
if ($("input[name='IsOccupant']:checked").val() == 1)
_IsOccupant = true;
alert(rdValue + " " + _IsOccupant);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form id="frm">
<label>True</label>
<input type="radio" id="rbOwner" value="1" name="IsOccupant" required="" />
<label>False</label>
<input type="radio" id="rbOccupant" value="2" name="IsOccupant" required="" />
</form>
<button id="btn">Click Me</button>
I am wondering why sometime my code upon publish failed to determine the checkbox value(Checked checkbox). But when I manually debug it it returns the correct value. Does anyone knows the reason for this?.
Wrap your code inside
$(document).ready(function(){
// Your code goes here
$("#btn").on("click",()=>{
const rdValue = $("#frm").serialize();
var _IsOccupant = false;
if ($("input[name='IsOccupant']:checked").val() == 1)
_IsOccupant = true;
alert(rdValue + " " + _IsOccupant);
});
})
This will ensure your JavaScript executes only when the document is fully loaded.
To take the values from an input tag kind is necessary to use the .value function instead of .val
Is something similar to this:
<!DOCTYPE html>
<html>
<head>
<title>
Get value of selected
radio button
</title>
</head>
<body>
<p>
Select a radio button and click on Submit.
</p>
Gender:
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Others">Others
<br>
<button type="button" onclick="displayRadioValue()">
Submit
</button>
<br>
<div id="result"></div>
<script>
function displayRadioValue() {
var ele = document.getElementsByName('gender');
for(i = 0; i < ele.length; i++) {
if(ele[i].checked)
document.getElementById("result").innerHTML
= "Gender: "+ele[i].value;
}
}
</script>
</body>
</html>
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Others">Others
<br>
<button type="button" onclick="displayRadioValue()">
Submit
</button>
<br>
<div id="result"></div>

Using Javascript To Show Values From HTML

I'm trying to create a HTML Page with multiple forms, and I would like
to show the values from the form on the same page (wiping the original HTML), but after using the button, nothing shows up (the page like reloaded)
Here's the code for HTML :
function Results() {
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var gender = document.getElementById('gender').value;
var date = document.getElementById('birthday').value;
if (document.getElementById('genderM').checked) {
gender = document.getElementById('genderM').value;
} else if (document.getElementById('genderF').checked) {
gender = document.getElementById('genderF').value;
}
document.writeIn("<h3>Thank You! Here's Your Precious Data! </h3>"); document.writeIn("<p> Your Name Is : </p>" + fname + lname); document.writeIn("<p> Gender : " + gender); document.writeIn("<p> Birthday : " + birthday);
document.getElementById('forms').innerHTML = forms;
}
<!DOCTYPE HTML>
<html>
<head>
<title> The Page Number 2 </title>
<link rel="stylesheet" type="text/css" href="page2.css">
</head>
<body>
<h1> Please fill in the form for exciting contents! </h1>
<hr size="5px" color="black">
<div id="forms" class="forms">
<form onsubmit="Results()" method="post">
<div class="textFirst">
First Name
</div>
<input id="fname" type="text" name="fname"> <br>
<br>
<div class="textLast">
Last Name <br>
</div>
<input id="lname" type="text" name="lname"> <br>
<br>
<div class="textGender">
Gender <br>
<input id="genderM" type="radio" name="gender" value="male"> Male <br>
<input id="genderF" type="radio" name="gender" value="female"> Female <br>
</div>
<br>
<div class="textBirth">
Birthday <br>
</div>
<input id="birthday" type="date" name="birthday"> <br>
<input id="submit" class="buttonagain" type="submit" value="Submit!" />
</form>
</div>
</body>
</html>
Any ideas what should I do?
Edit : I'm not able to use php or server for this
Your code is riddled with syntax errors: missing parentheses, missing + operators, etc.
document.writeIn (with an uppercase I) is not a function; document.writeln (with a lowercase L) is.
<script> tags aren't self-closing, i.e. you have to write <script src="scriptPage2.js"></script>
document.getElementById('gender') returns null, because there is no element with id="gender".
You're trying to write birthday but you never declared that variable.
I have no idea what you're trying to accomplish with document.getElementById('forms').innerHTML = forms;
In general, you should make use of the browser's built-in debugger to catch all these errors. If you're using Chrome or Firefox, press Ctrl+Shift+I (in IE or Edge, press F12) and open the "Console" tab; you will see all the errors there as the JS parser encounters them.
Once that's all fixed, remove the submit event handler from <form>, and change your submit button like this:
<input id="submit" class="buttonagain" type="button" onclick="Results()" value="Submit!" />
Note the change of type from submit to button. This will prevent the page from reloading, which is the expected behavior when submitting a form.
You don't need the return and ; when calling a js function in html
<form onsubmit="Results()" method="post">
This is your answer.
function Results() {
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var gender;
var date = document.getElementById('birthday').value;
if (document.getElementById('genderM').checked) {
gender = "Male";
} else {
gender = "Female"
}
document.writeln("<h3>Thank You! Here's Your Precious Data! </h3>");
document.writeln("<p> Your Name Is : </p>" + fname + " " + lname);
document.writeln("<p> Gender : " + gender);
document.writeln("<p> Birthday : " + date);
document.getElementById('forms').style.display = "none";
}
<!DOCTYPE HTML>
<html>
<head>
<title> The Page Number 2 </title>
<link rel="stylesheet" type="text/css" href="page2.css">
</head>
<body>
<h1> Please fill in the form for exciting contents! </h1>
<hr size="5px" color="black">
<div id="forms" class="forms">
<form onsubmit="Results();" method="post">
<div class="textFirst">
First Name
</div>
<input id="fname" type="text" name="fname" required> <br>
<br>
<div class="textLast">
Last Name <br>
</div>
<input id="lname" type="text" name="lname"required> <br>
<br>
<div class="textGender">
Gender <br>
<input id="genderM" type="radio" name="gender" value="male" required> Male <br>
<input id="genderF" type="radio" name="gender" value="female"> Female <br>
</div>
<br>
<div class="textBirth">
Birthday <br>
</div>
<input id="birthday" type="date" name="birthday"required> <br>
</div>
<input id="submit" class="buttonagain" type="submit" value="Submit!" />
</div>
</form>
</body>
</html>

Javascript won't output values from input box

I want to user to press submit button so that their name and age is displayed in the input box with name="output"?
I have 3 input boxes, one asking for name and the other for age while the other one provides output. I am trying to use the function output() to display the last input box.
I am confused about where I am going wrong, do I need a .value?
<!doctype html>
<html>
<head>
<style>
.formdiv{
align: center;
}
</style>
</head>
<body>
<script language="javascript" type="text/javascript">
function output(){
var name = getElementByName('firstName');
var Age= getElementByName('age');
var out = document.write(name+Age);
document.getElementByName('output') = out;
}
</script>
<h1><strong><em><center>Payment Details</center></em></strong> </h1>
<div class="formdiv">
<fieldset><center>
<legend> Enter the following Info:</legend>
<br />
<label> Name </label>
<input type="text" name="firstName" placeholder="John" required="required"></input>
<br/>
<br/>
<label>Age </label>
<input type="number" name="age" maxlength="2" required="required"></input>
</fieldset>
</center>
</div>
<div>
<center>
<button onClick="output()">Submit</button><br/>
<label for="output">Output</label>
<br/>
<input type="textbox" name="output"></input>
</center>
</div>
</body>
</html>
Here's a working version of your code.
There's no method getElementByName (but getElementsByName) - you should use document.getElementById() (Read about it here)
You should use the value of the input element.
<!doctype html>
<html>
<head>
<style>
.formdiv{
align: center;
}
</style>
</head>
<body>
<script language="javascript" type="text/javascript">
function output(){
var name = document.getElementById('firstName').value;
var Age= document.getElementById('age').value;
document.getElementById('output').value = name+Age;
}
</script>
<h1><strong><em><center>Payment Details</center></em></strong> </h1>
<div class="formdiv">
<fieldset><center>
<legend> Enter the following Info:</legend>
<br />
<label> Name </label>
<input type="text" id="firstName" placeholder="John" required="required"></input>
<br/>
<br/>
<label>Age </label>
<input type="number" id="age" maxlength="2" required="required"></input>
</fieldset>
</center>
</div>
<div>
<center>
<button onClick="output()">Submit</button><br/>
<label for="output">Output</label>
<br/>
<input type="textbox" id="output"></input>
</center>
</div>
</body>
</html>
getElementsByName (note: Elements, not Element) returns a list of Elements, in this case your <input>s. So first of all, you need to select the first (in your case your only one) using getElementsByName(...)[0]. Then you get one Element.
However you do not want to output the entire element (which is an Object, not a String, and converted to a string it likely won't be what you expect), so you need to select the value property of that Element. So yes, you need to add .value, just as you assumed:
function output(){
var name = getElementsByName('firstName')[0].value;
var Age= getElementsByName('age')[0].value;
Then, document.write writes the argument to a new document directly, which results in an emtpy page with nothing else on it but that string. This isn't what you want, so you don't need that. ALl you do want is to assign a new variable called out with that string:
var out = name+Age;
Then to assigning the new value to the output field - you don't want to replace the Element by a string (that wouldn't even work), but it's value, so you need the .value again:
document.getElementsByName('output')[0].value = out;
}
That should do the trick.
(In addition to that, you might want to use name + " " + Age instead of simply name+Age, as otherwise you end up with "John Doe23" instead of "John Doe 23" which you likely want)
There are a few things wrong with your code:
there is no such thing as getElementByName - it is getElementById
changing to the above, you need to add ids to your input elements
you need to use the value of the returned object from getElementById
The above will get your code working, but also, the center tag is obsolete and you shouldn't use it
Inputs are self closing tags so you don't need </input>
<!doctype html>
<html>
<head>
<style>
.formdiv {
align: center;
}
</style>
</head>
<body>
<script language="javascript" type="text/javascript">
function output() {
var name = document.getElementById('firstName').value;
var Age = document.getElementById('age').value;
var out = name + Age;
document.getElementById('output').value = out;
}
</script>
<h1><strong><em><center>Payment Details</center></em></strong> </h1>
<div class="formdiv">
<fieldset>
<center>
<legend>Enter the following Info:</legend>
<br />
<label>Name</label>
<input type="text" name="firstName" id="firstName" placeholder="John" required="required"></input>
<br/>
<br/>
<label>Age</label>
<input type="number" name="age" id="age" maxlength="2" required="required"></input>
</fieldset>
</center>
</div>
<div>
<center>
<button onClick="output()">Submit</button>
<br/>
<label for="output">Output</label>
<br/>
<input type="textbox" name="output" id="output"></input>
</center>
</div>
</body>
</html>

How to compare user input with attribute values in JavaScript?

I have a code like this and I want to compare in a loop the attribute values of name with user entered input stored in variable "user". How can I do this?
<form>
<input type="radio" name="two">
<input type="radio" name="three">
<input type="radio" name="four">
<input type="radio" name="five">
<input type="radio" name="six">
</form>
See this answer for an example of how to loop through radio buttons in native javascript, quoted here for convenience:
<html>
<head>
<script>
var userChoice;
var setUserChoice = function(event) {
event.preventDefault();
var choices = event.target.userChoice;
for (var i =0; i < choices.length; i++) {
if (choices[i].checked) {
userChoice = choices[i].value;
}
}
event.target.choice.value = userChoice;
}
window.onload = function() {
var form = document.getElementById('userInput');
form.addEventListener('submit', setUserChoice, false);
};
</script>
</head>
<body>
<form id="userInput">
<input type="radio" name="userChoice" id="userChoice_rock" value="rock">Rock</input> </br>
<input type="radio" name="userChoice" id="userChoice_paper" value="paper">Paper</input> </br>
<input type="radio" name="userChoice" id="userChoice_scissors"value="scissors">Scissors</input> </br>
<input type="radio" name="userChoice" id="userChoice_lizard" value="lizard">Lizard</input> </br>
<input type="radio" name="userChoice" id="userChoice_spock" value="spock">Spock</input> </br>
<input type="submit" value="Enter" /></br>
<output name="choice"></output>
</form>
</body>
</html>
You can compare tha values like in this fiddle: http://jsfiddle.net/5wd8p/
HTML
<form action="demo.html" id="myForm">
<form>
<input type="radio" name="two">
<input type="radio" name="three">
<input type="radio" name="four">
<input type="radio" name="five">
<input type="radio" name="six">
</form>
<input type="submit" value="Submit">
</form>
JQuery
$(function () {
// Handler for .ready() called.
var user = "three"; //default value: depends on youur code..
//Loop through each radio element of the DOM
$("input[type=radio]").each(function(){
//Compare values of the "name" attribute and the user var
if (user == $(this).attr("name")){
alert("Same: " + $(this).attr("name"));
}else{
alert("Different: " + $(this).attr("name"));
}
});
});
try this:
document.getElementsByName(user)[0]

Form validation in JSP using JavaScript

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<style type="text/css">
*{
font-family: cursive;
}
</style>
<script type="text/javascript">
function validate()
{
var a = document.getElementById("a");
var b = document.getElementById("b");
var valid = true;
if(a.value.length<=0 || b.value.length<=0)
{
alert("Don't leave the field empty!");
valid = false;
}
else{
if(!IsNumeric(a.value) || !IsNumeric(b.value))
alert("Enter a number");
valid = false;
}
return valid;
};
</script>
</head>
<body bgcolor="#CDCDCC" font-family="cursive" font-size="20px;" font-weight="bold">
<h2>Welcome <%=request.getParameter("uname")%>! Enter the numbers and the operation that you want to perform: </h2>
<form font-size="75px;" action ="serv" method="get" onsubmit="return validate();" >
<hr/>
Enter the 1st number: <input type="text" name="a" /><br/>
Enter the 2st number: <input type="text" name="b" /><br/><br/>
<label>Add</label><input type="radio" name="option" value="Add" /><br/>
<label>Subtract</label><input type="radio" name="option" value="Subtract"/><br/>
<label>Multiply</label><input type="radio" name="option" value="Multiply"/><br/>
<label>Divide</label><input type="radio" name="option" value="Divide" /><br/>
<input type="submit" value="Submit" />
</form>
</body>
This is my JSP and I've written a JavaScript function validate() that validates the user input against blank space and String.
My problem is that when i click on the submit button, for correct integer input, it is working. If an invalid input is given, i get a blank page. Can someone help me out with what the problem is and what is that i should modify? Thanks.
In you javascript you are checking via ID but there is no ID for input fields.
<input type="text" name="a" id ="a"/>
<input type="text" name="b" id="b" />
to check if a input is string or not use isNAN() like the following way
if(isNaN(a) || isNaN(b)){
alert("enter a number");}
Following is the complete working example
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<style type="text/css">
*{
font-family: cursive;
}
</style>
<script type="text/javascript">
function validate()
{
var a = document.getElementById("a");
var b = document.getElementById("b");
var c = document.getElementById("a").value;
var d = document.getElementById("b").value;
var valid = true;
if(a.value.length<=0 || b.value.length<=0)
{
alert("Don't leave the field empty!");
valid = false;
}
else{
if(isNaN(c) || isNaN(d)){
alert("Enter a number");
valid = false;}
}
return valid;
};
</script>
</head>
<body bgcolor="#CDCDCC" font-family="cursive" font-size="20px;" font-weight="bold">
<h2>Welcome <%=request.getParameter("uname")%>! Enter the numbers and the operation that you want to perform: </h2>
<form font-size="75px;" action ="serv" method="get" onsubmit="return validate();" >
<hr/>
Enter the 1st number: <input type="text" name="a" id="a" /><br/>
Enter the 2st number: <input type="text" name="b" id="b" /><br/><br/>
<label>Add</label><input type="radio" name="option" value="Add" /><br/>
<label>Subtract</label><input type="radio" name="option" value="Subtract"/><br/>
<label>Multiply</label><input type="radio" name="option" value="Multiply"/><br/>
<label>Divide</label><input type="radio" name="option" value="Divide" /><br/>
<input type="submit" value="Submit" />
</form>
</body>
Correct me if I'm wrong but your javascript function is looking for 'a' and 'b' IDs
And you don't have such... your input elements got names. add ids attributes...

Categories

Resources